I wrote a code to check whether a given graph is bipartite or not, but not sure why one code works but not the other.
The below doesn't work,
bool dfs(int i, int color, vector<vector<int>> &graph) {
if (visited[i] == -1) {
visited[i] = color;
for (int adj: graph[i])
return dfs(adj, !color, graph);
}
return (visited[i] == color);
}
bool isBipartite(vector<vector<int>> &graph) {
visited.assign(105, -1);
for (int i = 0; i < graph.size(); i++) {
if (visited[i] == -1)
if (!dfs(i, 0, graph)) return false;
}
return true;
}
vector<int> visited;
But when I change above to this
bool dfs(int i, int color, vector<vector<int>> &graph) {
if (visited[i] == -1) {
visited[i] = color;
for (int adj: graph[i])
if (!dfs(adj, !color, graph)) {
return false;
}
}
return (visited[i] == color);
}
bool isBipartite(vector<vector<int>> &graph) {
visited.assign(105, -1);
for (int i = 0; i < graph.size(); i++) {
if (visited[i] == -1)
if (!dfs(i, 0, graph)) return false;
}
return true;
}
vector<int> visited;
it Works, Can anyone tell why ? Notice that only line 5th and 6th in dfs function got changed.
shouldn't both code work since they seem to work same ?
In your first code snippet,
for (int adj: graph[i])
return dfs(adj, !color, graph);
what happens is you're returning within the first iteration of the for-loop. So for each node, you're only checking one of its neighbors, and ignoring the rest.
Note that your second snippet is not entirely correct either. You're missing a case where the node has no neighbors, or all of its neighbors have correct colors:
bool dfs(int i, int color, vector<vector<int>> &graph) {
if (visited[i] == -1) {
visited[i] = color;
for (int adj: graph[i])
if (!dfs(adj, !color, graph)) {
return false;
}
return true;
}
return (visited[i] == color);
}