Google/LintCode:M-图是否是树

49 篇文章 0 订阅
30 篇文章 0 订阅

题目


题目来源:Link


给出 n 个节点,标号分别从 0 到 n - 1 并且给出一个 无向 边的列表 (给出每条边的两个顶点), 写一个函数去判断这张`无向`图是否是一棵树

 注意事项

你可以假设我们不会给出重复的边在边的列表当中. 无向边 [0, 1] 和 [1, 0] 是同一条边, 因此他们不会同时出现在我们给你的边的列表当中。

样例

给出n = 5 并且 edges = [[0, 1], [0, 2], [0, 3], [1, 4]], 返回 true.

给出n = 5 并且 edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], 返回 false.


分析


(1)利用树的特性,树的边一定是 n-1,若边数大于n-1,则一定是图
(2)对于边= n-1 , 可能是几个连同分量组成的图,用 bfs 随便选择起点遍历,如果遍历完成后,节点数为 n , 则为树


代码


public class Solution {
    /**
     * @param n an integer
     * @param edges a list of undirected edges
     * @return true if it's a valid tree, or false
     */
    public boolean validTree(int n, int[][] edges) {
        // Write your code here
        
        if(n==0) return false;
        
        if(n==1) return true;
        
        if(edges==null || edges.length==0) return false;
        
        //build the "graph"
        if(edges.length==n-1){
            
            int start = edges[0][0];
            
            Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
            int m = edges.length;
            for(int i=0; i<m; i++){
                int a = edges[i][0];
                int b = edges[i][1];
                if(!map.containsKey(a))
                    map.put(a, new HashSet<Integer>());
                map.get(a).add(b);
                if(!map.containsKey(b))
                    map.put(b, new HashSet<Integer>());
                map.get(b).add(a);
            }
            
            return bfs(map, n, start);
               
        }else return false;
    }
    boolean bfs(Map<Integer, Set<Integer>> map, int n, int start){
        Queue<Integer> q = new LinkedList<Integer>();
        q.add(start);
        Set<Integer> visited = new HashSet<Integer>();
        visited.add(start);
        while(!q.isEmpty()){
            int t = q.poll();
            //visited.add(t);
            Set<Integer> tmp = map.get(t);
            for(Integer tt:tmp){
                if(!visited.contains(tt)){
                    q.add(tt);
                    visited.add(tt);
                }
            }
        }
        if(visited.size()<n)
            return false;
        else 
            return true;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值