1. 程式人生 > >[CareerCup] 4.2 Route between Two Nodes in Directed Graph 有向圖中兩點的路徑

[CareerCup] 4.2 Route between Two Nodes in Directed Graph 有向圖中兩點的路徑

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

LeetCode和CareerCup中關於圖的題都不是很多,LeetCode中只有三道,分別是Clone Graph 無向圖的複製Course Schedule 課程清單Course Schedule II 課程清單之二。目前看來CareerCup中有關圖的題在第四章中僅此一道,這是一道關於有向圖的題,書中是用java來做的,我們用c++來做時要定義圖和節點,這裡參考了之前那道

Clone Graph 無向圖的複製中關於無向圖的定義,並且在裡面加入了一個列舉類變數state,來幫助我們遍歷。這種找兩點之間路徑的題就是遍歷的問題,可以用BFS或DFS來解,先來看BFS的解法,如下所示:

//Definition for directed graph.
enum State {
    Unvisited, Visited, Visiting
};

struct DirectedGraphNode {
   int label;
   State state;
   vector<DirectedGraphNode *> neighbors;
   DirectedGraphNode(
int x) : label(x) {}; }; struct DirectedGraph { vector<DirectedGraphNode*> nodes; }; class Solution { public: bool search(DirectedGraph *g, DirectedGraphNode *start, DirectedGraphNode *end) { queue<DirectedGraphNode*> q; for (auto a : g->nodes) a->state = Unvisited; start
->state = Visiting; q.push(start); while (!q.empty()) { DirectedGraphNode *node = q.front(); q.pop(); for (auto a : node->neighbors) { if (a->state == Unvisited) { if (a == end) return true; else { a->state = Visiting; q.push(a); } } } node->state = Visited; } return false; } };