您的位置:首页 > Web前端 > Node.js

4.1 Route Between Nodes

2015-10-27 14:21 423 查看
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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Graph