[Leetcode] 261. Graph Valid Tree 解题报告

来源:互联网 发布:义乌淘宝培训班要求 编辑:程序博客网 时间:2024/05/18 18:00

题目

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.

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.

思路

一个图是一棵合法的树的充要条件是:1)图的边的个数比顶点个数少1;2)图中没有任何环。我们将每一个顶点都初始化成为一个单独的集合,然后对于每一条边,检查它的两个顶点原来是否属于同一个集合,一旦是就说明构成了环,直接返回false;否则就将这两个顶点所属的两个集合进行合并。

代码

class Solution {public:    bool validTree(int n, vector<pair<int, int>>& edges) {        if(edges.size() + 1 != n) {            return false;        }        vector<int> parents(n, -1);        for(int i = 0; i < n; ++i) {            parents[i] = i;        }        for(auto val : edges) {            int par1 = val.first, par2 = val.second;            while(par1 != parents[par1]) {                par1 = parents[par1];            }            while(par2 != parents[par2]) {                par2 = parents[par2];            }            if(par1 != par2) {                parents[par1] = par2;            }            else {                return false;            }        }        return true;    }};

原创粉丝点击