• 261. Graph Valid Tree


    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.

    For example:

    Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.

    Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.

    Hint:

    1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? 
    2. According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

    Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

    Similar: 
    • 207. Course Schedule
    • 323. Number of Connected Components in an Undirected Graph
     1 public class Solution {
     2     public boolean validTree(int n, int[][] edges) {
     3         int[] pt = new int[n];
     4         for (int i=0; i<n; i++) { pt[i] = i; }
     5         
     6         for (int[] edge : edges) {
     7             int root1 = find(pt, edge[0]);
     8             int root2 = find(pt, edge[1]);
     9             
    10             if (root1 == root2) return false; // find circle
    11             
    12             pt[root1] = root2; // union
    13         }
    14         return edges.length == n-1; // tree w/ n notes have n-1 edges
    15     }
    16     private int find(int[] pt, int i) {
    17         while (pt[i] != i) {
    18             pt[i] = pt[pt[i]];
    19             i = pt[i];
    20         }
    21         return i;
    22     }
    23 }
  • 相关阅读:
    python module introduce
    python代码基
    20100911部署更新
    汉王ocr
    wsgi
    css布局模板
    Making a simple web server in Python.
    20100910更新部署
    tw.forms usage
    python web shell
  • 原文地址:https://www.cnblogs.com/joycelee/p/5310560.html
Copyright © 2020-2023  润新知