lintcode graph-valid-tree 图是否是树

来源:互联网 发布:bp算法的基本思想 编辑:程序博客网 时间:2024/06/04 19:22

问题描述

http://www.lintcode.com/zh-cn/problem/graph-valid-tree/

笔记

参考
有向图也可参考下面这个链接
https://segmentfault.com/a/1190000004262708

http://www.cnblogs.com/jcliBlogger/p/4738788.html

树,其实是不存在环而且没有孤立节点的图。

As suggested by the hint, just check for cycle and connectedness in the graph.

首先建立邻接矩阵neighbor,如对于edges = [[0, 1], [0, 2], [0, 3], [1, 4]]

neighbor[0] = {1, 2, 3}neighbor[1] = {0}...

然后建立已访问的vector:
vector<bool> visited(n, false);
紧接着遍历图,看是否存在环。存在环则不是树。
最后看visited是不是每个节点都遍历了(判断是否存在孤立节点)。如果不是,则不是树。

代码

class Solution {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) {        // Write your code here        vector<vector<int>> neighbor(n);        for (auto i: edges)        {            neighbor[i[0]].push_back(i[1]);            neighbor[i[1]].push_back(i[0]);        }        vector<bool> visited(n, false);        if (hasCycle(neighbor, visited, -1, 0))            return false;        for (auto i: visited)            if(!i)                return false;        return true;    }    bool hasCycle(vector<vector<int>> &neighbor, vector<bool> &visited, int par, int kid)    {        if (visited[kid])            return true;        visited[kid] = true;        for (auto i: neighbor[kid])        {            if (par != i && hasCycle(neighbor, visited, kid, i))//先排除par==i的情况,这种情况其实是neighbor数组定义的时候固有的特性,不算成环。                return true;        }        return false;    }};
0 0
原创粉丝点击