public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); if (nodes == null || nodes.size() == 0) return ans; HashSet<UndirectedGraphNode> set = new HashSet<>(); for (UndirectedGraphNode node : nodes) { if (set.contains(node)) continue; Queue<UndirectedGraphNode> q = new LinkedList<>(); List<Integer> temp = new ArrayList<>(); q.offer(node); while (!q.isEmpty()) { UndirectedGraphNode cur = q.poll(); if (set.contains(cur)) continue; temp.add(cur.label); set.add(cur); for (UndirectedGraphNode neighbor : cur.neighbors) { q.offer(neighbor); } } // I don't understand why the OJ ask this Collections.sort(temp); ans.add(new ArrayList<Integer>(temp)); } return ans; }
近期评论