Questions: given a graph where nodes have undirected neighbours, partition them into connected groups
Idea: Pretty much the same as the previous solution for directed neighbours. It does not really matter whether it is directed or not. Since I already give a UnionFind solution in the previous question. This one we use DFS. Note that this one cannot be used in the previous directed graph, this is because you cannot determine when to create a new group for the connected components.
Example
IN: 1 and 2, 1 and 3, 2 and 3, 4 and 5
OUT: 1,2,3 and 4,5
/**
* Definition for Undirected graph.
* class UndirectedGraphNode {
* int label;
* ArrayList<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
/*
* @param nodes: a array of Undirected graph node
* @return: a connected set of a Undirected graph
*/
public List<List<Integer>> connectedSet(List<UndirectedGraphNode> nodes) {
Set<UndirectedGraphNode> visited = new HashSet();
List<List<Integer>> res = new LinkedList();
for(UndirectedGraphNode node : nodes) {
if (visited.contains(node)) continue;
List<Integer> curList = new LinkedList<>();
collect(node, visited, curList);
res.add(curList);
}
return res;
}
private void collect(UndirectedGraphNode host,
Set<UndirectedGraphNode> visited,
List<Integer> list) {
if (!visited.contains(host)) {
visited.add(host);
list.add(host.label);
}
for(UndirectedGraphNode node: host.neighbors) {
if (visited.contains(node)) continue;
visited.add(node);
list.add(node.label);
collect(node, visited, list);
}
}
}