Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its neighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.)node
Solution
BFS + Hashmap -------- get all nodes by BFS, record visited by hashmap優化
public class Solution { /** * @param nodes a array of Undirected graph node * @return a connected set of a Undirected graph */ //優化點------boolea[] visited instead of arraylist.contains() public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) { int m = nodes.size(); Map<UndirectedGraphNode, Boolean> visited = new HashMap<>(); for (UndirectedGraphNode node : nodes){ visited.put(node, false); } List<List<Integer>> result = new ArrayList<>(); for (UndirectedGraphNode node : nodes){ if (visited.get(node) == false){ bfs(node, visited, result); } } return result; } public void bfs(UndirectedGraphNode node, Map<UndirectedGraphNode, Boolean> visited, List<List<Integer>> result){ List<Integer>row = new ArrayList<>(); Queue<UndirectedGraphNode> queue = new LinkedList<>(); visited.put(node, true); queue.offer(node); while (!queue.isEmpty()){ UndirectedGraphNode u = queue.poll(); row.add(u.label); for (UndirectedGraphNode v : u.neighbors){ if (visited.get(v) == false){ visited.put(v, true); queue.offer(v); } } } Collections.sort(row); result.add(row); } }