Google/LintCode:M-图是否是树
来源:互联网 发布:宁波淘宝托管 编辑:程序博客网 时间:2024/05/16 07:35
题目
题目来源: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
- Google/LintCode:M-图是否是树
- LintCode:图是否是树
- [LintCode]图是否是树
- 图是否是树-LintCode
- lintcode(178)图是否是树
- lintcode graph-valid-tree 图是否是树
- *[Lintcode] Graph Valid Tree 图是否是树
- Google/LintCode:M-寻找峰值
- Google/LintCode:M-最大平均值子数组
- Google/LintCode:M-超级丑数
- Google/LintCode:M-搜索二维矩阵 II
- Google/LintCode:M-Palindrome Partitioning II
- LintCode:M-克隆图
- Google/LintCode:M-Insert Delete GetRandom O(1)
- Google/LintCode:M-摊平嵌套的列表
- Google/LintCode:M-合并k个排序链表
- Google/LintCode:M-带最小值操作的栈
- LintCode(M)
- checkstyle直接用java命令,不调用eclipse等IDE
- 几款适合vue移动端的第三方小组件
- 在Hibernate中@ManyTOMany 单/双向外键关联
- sqlserver中如何实现时间按月,日,小时等时间分组查询
- Java maven项目集成ueditor(百度本编辑器)插件详解
- Google/LintCode:M-图是否是树
- python调用第三方邮件接口
- json语法格式
- 最新MySQL5.7.19解压版安装指南
- SE03可以unlock CR
- 用随机森林分类算法进行Iris 数据分类训练,是怎样的体验?
- html屏蔽右键、禁止复制与禁止查看源代码
- Ehcache使用教程
- javascript读写txt 并根据换行符空格符比较数组