Leetcode:graph Valid Tree && summary:detect cycle in directed graph and undirected graph

Source: Internet
Author: User

Given n nodes labeled from 0 to n-1returntruereturnfalse. Note:you can assume that no duplicate edges would appear in edges. Since all edges be undirected, [0, 1] is the same as [1, 0] and thus would not be appear together in edges.

This problem can is solved by using the Union find, reference this blog:1190000003791051

Complexity of

Time O (n^m) space O (1)

Ideas

To determine whether an input edge can form a tree, we need to identify two things:

    1. Whether these edges form a loop, or if there is a ring, does not constitute a tree

    2. Whether these edges can connect all nodes, and if there are non-connected nodes, does not constitute a tree

Because you do not need to know what the exact tree looks like, as long as you know the connected relationship, the Union find ( and check) is a better approach than deep-first search. We define a set of data structures and provide standard four interfaces:

    • unionPut two nodes in a collection

    • findFind the collection number that the node belongs to

    • areConnectedDetermine if two nodes are a collection

    • countReturns the number of independent collections in this and check set

See this article for a detailed look at the principles of the collection. Simply put, the first is to build an array, node 0 to node n-1, at first, they are independent of their own collection. The number of the collection is the node number. Then, each time the union operation, we put the whole and check, all and the first node belongs to the same set number of nodes, the collection number is changed to the second node's collection number. This allows the node of a collection to be under the same set number. We iterate through the input, add all the edges to our and check the focus, add the same time to determine whether there is a loop. Finally, if you have only one collection in the set, you can build the tree.

Attention

Because the Union method returns a Boolean to determine if a loop is generated, if two nodes are already in a set, it returns false, indicating that there is a loop

1  Public classSolution {2      Public BooleanValidtree (intNint[] edges) {3Unionfind uf =Newunionfind (n);4          for(inti=0; i<edges.length; i++) {5             if(Uf.areconnected (Edges[i][0], edges[i][1]))return false;6             Else {7Uf.union (Edges[i][0], edges[i][1]);8             }9         }Ten         returnUf.count () ==1; One     } A      -      Public classUnionfind { -         int[] IDs;//Union ID for each node the         intCnt//The number of independent Union -          -          PublicUnionfind (intsize) { -              This. ids =New int[size]; +              for(inti=0; i<size; i++) { -Ids[i] =i; +             } A              This. CNT =size; at         } -          -          Public BooleanUnionintIintj) { -             intsrc =find (i); -             intDST =find (j); -             if(src! =DST) { in                  for(intk=0; k<ids.length; k++) { -                     if(Ids[k] = =src) { toIDS[K] =DST; +                     } -                 } thecnt--; *                 return true; $             }Panax Notoginseng             return false; -         } the          +          Public intFindinti) { A             returnIds[i]; the         } +          -          Public BooleanAreconnected (intIintj) { $             returnFind (i) = =find (j); $         } -          -          Public intcount () { the             returnCNT; -         }Wuyi     } the}

Summary:

Dectect cycle in directed graph:

Detect cycle in a directed graph is using a DFS. Depth first traversal can be used to detect cycle in a Graph. DFS for a connected graph produces a tree. There is a-cycle in a-graph only if there are a back edge present in the graph. A back Edge was an edge, that's from a node to itself (Selfloop), or one of its ancestor in the tree produced by DFS. In the following graph, there is 3 back edges, marked with cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph.

To detect a back edge, we can keep track of vertices currently in recursion stack of function for DFS traversal. If we reach a vertex that's already in the recursion stack, then there are a cycle in the tree. The edge that connects current vertex to the vertex in the recursion stack are back edge. We have used recstack[] array to keep track of vertices in the recursion stack.

Detect Cycle in undirected graph:

Method 1:union Find The time complexity of the union-find algorithm is O (ELOGV).

Method 2:dfs + parent node like directed graphs, we can use DFS to detect cycle in an undirected graph In O (v+e) time. We do a DFS traversal of the given graph. For every visited Vertex ' V ', if there is a adjacent ' u ' such that you are already visited and u are not the parent of V, then th Ere is a cycle in graph. If we don ' t find such an adjacent for any vertex, we say this there is no cycle. The assumption of this approach was that there be no parallel edges between any of the vertices.

Leetcode:graph Valid Tree && summary:detect cycle in directed graph and undirected 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.