-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 19 May | 785. Is Graph Bipartite?.cpp
- Loading branch information
1 parent
8f255ab
commit 3730204
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
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,31 @@ | ||
class Solution { | ||
public: | ||
bool isBipartite(vector<vector<int>>& graph) { | ||
int n = graph.size(); | ||
vector<int> color(n,0); | ||
|
||
for(int node = 0; node < n; node++){ | ||
if(color[node] != 0) continue; | ||
|
||
queue<int> q; | ||
q.push(node); | ||
color[node] = 1; | ||
|
||
while(!q.empty()){ | ||
int curr = q.front(); | ||
q.pop(); | ||
|
||
for(int adjN : graph[curr]){ | ||
if(color[adjN] == 0){ | ||
color[adjN] = -color[curr]; | ||
q.push(adjN); | ||
} | ||
else if(color[adjN] != -color[curr]){ | ||
return false; | ||
} | ||
} | ||
} | ||
} | ||
return true; | ||
} | ||
}; |