[LintCode][Tree] Graph Valid Tree

Problem

More Discussions

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.

Notice

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.

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.

Solution

問題的本質就是判斷圖中有沒有環,并且所有的點都聯通。
那么我們可以用DFS來遍歷所有的點,同時做一些判斷

  1. 給每個點設顏色:0:未遍歷過 1:遍歷過一次 2:遍歷過2次。那么很容易的可以知道如果有一個點遍歷過2次,那肯定存在環。如果DFS之后有一個點從未遍歷過,那這個點就在另一個圖中,所以也無法構成數。
  2. 另外在判斷當前點的下面的遍歷節點時,我們要出去它的父親節點,這樣可以避免一條邊被重復遍歷。
class Solution {
private:
    vector<vector<int>> nodes;
    vector<int> nodeColor;
    
public:
    /**
     * @param n an integer
     * @param edges a list of undirected edges
     * @return true if it's a valid tree, or false
     */
    bool validTree(int n, vector<vector<int>>& edges) {
        if (n == 0) {
            return true;
        }
        nodes.resize(n);
        nodeColor.resize(n);
        for(int i = 0; i < edges.size(); i++) {
            int node1 = edges[i][0];
            int node2 = edges[i][1];
            nodes[node1].push_back(node2);
            nodes[node2].push_back(node1);
        }
        for(int i = 0; i < nodeColor.size(); i++) {
            nodeColor[i] = 0;
        }
        bool result = check(0, -1);
        if (!result) {
            return false;
        }
        
        for(int i = 0; i < n; i++) {
            if (nodeColor[i] == 0) {
                return false;
            }
        }
        
        return true;
    }
    
    bool check(int index, int parentIndex) {
        nodeColor[index]++;
        if (nodeColor[index] == 2) {
            return false;
        }
        
        for(int i = 0; i < nodes[index].size(); i++) {
            if (nodes[index][i] != parentIndex) {
                bool result = check(nodes[index][i], index);
                if (!result) {
                    return false;
                }
            }
        }
        
        return true;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • 3.1 Graphs Represent a graph by Adjacency matrix -- spars...
    暗黑破壞球嘿哈閱讀 2,959評論 0 0
  • 尊敬的領導,老師,同學們: 大家中午好。我是09級新生王會。此刻我作為上屆學生會成員代表,能夠在此發言我倍感榮幸。...
    棟棟八閱讀 485評論 0 3
  • “梧桐更兼細雨,到黃昏,點點滴滴。這次第,怎一個愁字了得?”翻開詩集,墨色的仿宋體,清雋的印著易安的黃昏,于...
    微微一笑很虔誠閱讀 357評論 0 0
  • 我想來這個沒有人認識我的地方發畫~盡量每天打,等一段時間之后來看自己的進步~記錄一下我的成長 我的畫實在是問題很大...
    韓小小小旭閱讀 160評論 0 0