4.1 Route Between Nodes

来源:互联网 发布:2017最新网络热门话题 编辑:程序博客网 时间:2024/05/23 18:04

For all directed graph problem, I use struct DirectedGraphNode:

    struct DirectedGraphNode {        int label;        vector<DirectedGraphNode *> neighbors;        DirectedGraphNode(int x) : label(x) {};    };

Simply BFS traverse Graph:

    bool hasRoute(vector<DirectedGraphNode*> graph,                  DirectedGraphNode* s, DirectedGraphNode* t) {        // write your code here        queue<DirectedGraphNode*> q;        q.push(s);        while(!q.empty()){            DirectedGraphNode* cur = q.front();            q.pop();            for(auto node : cur->neighbors) q.push(node);            if(cur == t) return true;        }        return false;    }

Note: BFS always first think about queue!

0 0