4.2 Given A directed graph, design an algorithm to find out whether there is a route between both nodes.
Leetcode and Careercup in the picture of the problem are not many, Leetcode only three, respectively, is the clone graph non-map copy, Course Schedule course list and Course Schedule II course List II. At present, it seems careercup in the fourth chapter of the title of the problem, this is a question about the graph, the book is to do with Java, we use C + + to define the graph and node, here reference to the previous clone graph without the copy of the graph of the definition of the non-map, And added an enum class variable state to help us traverse. This finding of the path between two points is the problem of traversal, you can use BFS or DFS to solve, first look at the BFS solution, as follows:
//Definition for directed graph.enumState {unvisited, visited, visiting};structDirectedgraphnode {intlabel; State State; Vector<directedgraphnode *>Neighbors; Directedgraphnode (intx): Label (x) {};};structdirectedgraph {vector<DirectedGraphNode*>nodes;};classSolution { Public: BOOLSearch (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; }};
[Careercup] 4.2 route between-Nodes in Directed graph has a path to two points in the graph