Graph Valid Tree

來源:互聯網
上載者:User

標籤:

Graph Valid TreeGiven 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.Have you met this question in a real interview? YesExample

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

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

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.

 

這一題lintcode上的中文我並不能理解是什麼意思。。於是就放上英文的。

大意是給你一個圖的節點數n,和邊的集合(整型二維數組),檢驗這個圖是不是一棵樹。

一個圖是不是一棵樹,要看這個圖是否是連通的,不連通的當然不是樹。

還要看有沒有環,樹是沒有環的。

用並查集(應該是這麼叫把?)的方法,將點合并,期間發現有環則 return false。

然後檢驗是否聯通,若有一點不連通則return false。

 1 public class Solution { 2     /** 3      * @param n an integer 4      * @param edges a list of undirected edges 5      * @return true if it‘s a valid tree, or false 6      */ 7     public boolean validTree(int n, int[][] edges) { 8         int flag[] = new int[n]; 9         for(int i=0;i<n;i++) {10             flag[i] = i;11         }12         13         for(int i=0;i<edges.length;i++) {14             int s = edges[i][0];15             int e = edges[i][1];16             if(flag[s] != flag[e]) {17                 int x = flag[e];18                 for(int j=0;j<n;j++) {19                     if(flag[j] == x) flag[j] = flag[s];20                 }21             }else return false;22         }23         24         25         26         for(int i=1;i<n;i++) {27             if(flag[0] != flag[i])return false;28         }29         30         return true;31     }32 }
View Code

 

Graph Valid Tree

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.