图是否是树-LintCode
来源:互联网 发布:琴房隔音 知乎 编辑:程序博客网 时间:2024/06/04 19:01
给出 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.
#ifndef C178_H#define C178_H#include<iostream>#include<vector>using namespace std;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 int len = edges.size(); if (len != n - 1) return false; vector<int> roots(n); for (int i = 0; i < n; ++i) roots[i] = i; for (int j = 0; j < edges.size(); ++j) { int root1 = root(roots, edges[j][0]); int root2 = root(roots, edges[j][1]); if (root1 == root2) return false; roots[root2] = root1; } return true; }private: int root(vector<int> roots, int id) { if (id == roots[id]) return id; return root(roots, roots[id]); }};#endif
阅读全文
0 0
- LintCode:图是否是树
- [LintCode]图是否是树
- 图是否是树-LintCode
- lintcode(178)图是否是树
- Google/LintCode:M-图是否是树
- lintcode graph-valid-tree 图是否是树
- *[Lintcode] Graph Valid Tree 图是否是树
- 图是否是树
- 图是否是树
- 图是否是树
- 图是否是树
- LintCode 判断一个二叉树树是否是另一个二叉树的子书
- lintCode 第一题,两个词是否是变位词
- 判断无向图是否是树
- 两个字符串是否是变位词(直接lintcode敲代码,一次通过,噢耶!)
- lintcode178. graph valid tree 图是否是树
- 算法爱好者——图是否是树 ? 待解决
- 判断是否是子树 和 判断二叉树是否平衡
- 非注解和注解的处理器映射器和适配器---SpringMVC学习笔记(三)
- 【python 图像检测】图像模糊检测算法
- ng-style用于背景图片的样式方法
- 每天一个linux命令(8):cp 命令
- 第十三篇:TCP中的四大定时器
- 图是否是树-LintCode
- 集合笔记
- hdu 6138 ac自动机
- 第十四篇:TCP的拥塞控制机制
- 在videoview中增加点击监听事件
- 微信小程序特殊效果合集第一期
- 每天一个linux命令(9):touch 命令
- 跟踪源码运行流程---SpringMVC学习笔记(四)
- java线程的几种状态