Hi,
For problem 19.6, as i understand, essentially we need to determine if the graph is bipartite. It seems it can be solved differently than the solution in the book, without doing BFS, in 2 steps:
-
We build a set of vertices that have no edges between them. We go through each vertex iteratively: start with empty set, then for each vertex we consider check if it has edges to any vertices already in the set and if it doesn’t, put it in the set.
-
Now consider remaining vertices (the ones not in the set we just built). Check if there are any edges between the remaining vertices. If there are no such edges, the graph is bipartite and the 2 sets represent the sought division. If there are such edges, the graph is not bipartite.
The time complexity is O(|V| + |E|) (provided we can mark the vertices in the 1st step so that each check will take O(1)) since in each step the number of edges we check is O(|E|). Also there is no need for a queue, as in BFS solution.
This algorithm will work whether the graph is connected or not.
I just thought this has a little bit simplier logic than the solution in the book.
Thanks,
Yev