#176 Route Between Two Nodes in Graph

时间:2022-01-23 17:59:12

题目描述:

Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

Example

Given graph:

A----->B----->C
 \     |
  \    |
   \   |
    \  v
     ->D----->E

for s = B and t = E, return true

for s = D and t = C, return false

题目思路:

这题我发现只能用bfs做,dfs做会超时(坑爹呀!)。bfs用简单的传统算法就好了。

Mycode(AC = 396ms):

/**
 * Definition for Directed graph.
 * struct DirectedGraphNode {
 *     int label;
 *     vector<DirectedGraphNode *> neighbors;
 *     DirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    /**
     * @param graph: A list of Directed graph node
     * @param s: the starting Directed graph node
     * @param t: the terminal Directed graph node
     * @return: a boolean value
     */
    bool hasRoute(vector<DirectedGraphNode*> graph,
                  DirectedGraphNode* s, DirectedGraphNode* t) {
        // write your code here
        stack<DirectedGraphNode *> sgraph;
        sgraph.push(s);
        
        // bfs to search the neighbors
        while (!sgraph.empty()) {
            DirectedGraphNode *node = sgraph.top();
            sgraph.pop();
            
            if (node->label == t->label) return true;
            
            for (int i = 0; i < node->neighbors.size(); i++) {
                sgraph.push(node->neighbors[i]);
            }
        }
        
        return false;
    }
};