I have a random graph represented by an adjacency matrix in Java, how can I find the connected components (sub-graphs) within this graph?
I have found BFS and DFS but not sure they are suitable, nor could I work out how to implement them for an adjacency matrix.
Any ideas?
Using scipy's sparse module,
Assuming your input is a dictionary from a
(label_1,label_2)
toweight
you can run this code:See full gist on github here
You need to allocate marks - int array of length n, where n is the number of vertex in graph and fill it with zeros. Then:
1) For BFS do the following:
2) For DFS do the following.
After performing any of this procedures, Components will have number of connected components, and for each vertex i, marks[i] will represent index of connected component i belongs.
Both complete on O(n) time, using O(n) memory, where n is matrix size. But I suggest you BFS as far as it doesn't suffer from stack overflow problem, and it doesn't spend time on recursive calls.
BFS code in Java:
You can implement DFS iteratively with a stack, to eliminate the problems of recursive calls and call stack overflow. The implementation is very similar to BFS with queue - you just have to mark vertices when you pop them, not when you push them in the stack.