forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request 7oSkaaa#1108 from LamaSalah32/main
add 19- Is Graph Bipartite? (Lama Salah).cpp
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
49 changes: 49 additions & 0 deletions
49
05- May/19- Is Graph Bipartite?/19- Is Graph Bipartite? (Lama Salah).cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
// Author: Lama Salah | ||
|
||
class Solution { | ||
public: | ||
vector<vector<int>> adj; // Adjacency list to represent the graph. | ||
vector<int> vis; // Array to keep track of node colors. | ||
|
||
// Recursive function to check if the graph is not bipartite. | ||
bool isNotBipartite(int node, int color) { | ||
vis[node] = color; // Assign the current node the specified color (0 or 1). | ||
|
||
bool ans = false; // Variable to store the result. | ||
|
||
for (auto& i : adj[node]) { | ||
if (vis[i] == -1) { | ||
// If the neighbor hasn't been visited, recursively call the function with the opposite color. | ||
ans |= isNotBipartite(i, color ^ 1); | ||
} else if ((color ^ 1) != vis[i]) { | ||
// If the neighbor has been visited and has the same color as the current node, the graph is not bipartite. | ||
return true; | ||
} | ||
} | ||
|
||
return ans; | ||
} | ||
|
||
bool isBipartite(vector<vector<int>>& graph) { | ||
adj.assign(graph.size(), vector<int>()); // Initialize the adjacency list. | ||
vis.assign(graph.size(), -1); // Initialize the vis array. | ||
|
||
// Build the adjacency list based on the given graph. | ||
for (int i = 0; i < graph.size(); i++) { | ||
for (auto& j : graph[i]) { | ||
adj[i].push_back(j); | ||
adj[j].push_back(i); | ||
} | ||
} | ||
|
||
// Iterate over each node in the graph. | ||
for (int i = 0; i < graph.size(); i++) { | ||
if (vis[i] == -1 && isNotBipartite(i, 0)) { | ||
// If the node hasn't been visited and the graph is not bipartite, return false. | ||
return false; | ||
} | ||
} | ||
|
||
return true; // The graph is bipartite. | ||
} | ||
}; |