Reputation: 97
So an old exam question was asked like that. I was wondering what that means, because a graph can be directed or not. In a directed graph it should be working like that (I guess):
Create two Arrays: A[], A_inverse[] //both in size N (N nodes exists), both arrays initalized with NULL
Run depth-first search on Graph G
save in A[] all Nodes which are visted
If(A.size < |N|) return false
G' = Reverse all edges of G
Run depth-first search on Graph G'
save in A_inverse[] all Nodes which are visted
If(A_inverse.size < |N|) return false
return true
For the time-complexity it is T(N) = 2*DFS + |E| + c. 2*DFS because im calling it twice (once for the G and once for G'). |E| because I need to reverse all Edges. c are all conditions and initializings. Is my algorithm correct?
Upvotes: 0
Views: 437
Reputation: 1303
In a strongly connected graph G, there must be a path from any node A to any (other) node B.
To start, note that there is a path from B to A in the flipped graph G' if and only if there is a path from A to B in the original graph G.
Assume the DFS starts at some origin node O.
First we show that if G is strongly connected, the algorithm returns true.
Now consider a graph G that is not strongly connected, i.e., there's a pair of nodes (A, B) such that there exists no path from A to B. We have to show that the algorithm returns false. There are two cases to consider:
We proved that the algorithm returns true if G is strongly connected and false otherwise. It is therefore correct.
Upvotes: 1