国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LeetCode Graph Valid Tree

2019-11-10 22:08:38
字體:
來源:轉載
供稿:網友

description: 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.

Notice

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.

Have you met this question in a real interview? Yes 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.

這個題目的重點的部分是 判斷graph進行遍歷時,進出的個數與原有的點的個數的對比

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 != edges.length) { return false; } Map<Integer, Set<Integer>> map = initializeGraph(n, edges); Queue<Integer> queue = new LinkedList<>(); Set<Integer> set = new HashSet<>(); queue.offer(0); set.add(0); int visit = 0; while (!queue.isEmpty()) { int node = queue.poll(); visit++; for (int root : map.get(node)) { if (set.contains(root)) { continue; } queue.offer(root); set.add(root); } } return visit == n; } PRivate Map<Integer, Set<Integer>> initializeGraph(int n, int[][] edges) { Map<Integer, Set<Integer>> graph = new HashMap<>(); for (int i = 0; i < n; i++) { graph.put(i, new HashSet<Integer>()); } for (int i = 0; i < edges.length; i++) { int u = edges[i][0]; int v = edges[i][1]; graph.get(u).add(v); graph.get(v).add(u); } return graph; }}
上一篇:95. Unique Binary Search Trees II

下一篇:堆 棧

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 玛曲县| 木兰县| 浦东新区| 滨海县| 隆尧县| 江源县| 彭水| 华亭县| 西畴县| 仪征市| 巴彦县| 陈巴尔虎旗| 若羌县| 延长县| 精河县| 金门县| 肥西县| 家居| 阿拉尔市| 长沙县| 大洼县| 三亚市| 白沙| 土默特右旗| 五家渠市| 巴彦淖尔市| 巴塘县| 南开区| 西丰县| 彰化县| 清苑县| 枞阳县| 海安县| 闻喜县| 双辽市| 博爱县| 金川县| 富蕴县| 中卫市| 富蕴县| 得荣县|