[Careercup] 4.2 route between, Nodes in Directed graph two-point path

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.