Skip to content

Commit

Permalink
Create 785.Is-Graph-Bipartite.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Sep 16, 2019
1 parent 4c4b1a2 commit 14c9e15
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions BFS/785.Is-Graph-Bipartite/785.Is-Graph-Bipartite.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph)
{
int n = graph.size();
vector<int>visited(n,-1);

for (int i=0; i<n; i++)
{
if (visited[i]!=-1)
continue;

queue<pair<int,int>>q;
q.push({i,0}); // {node, group}
visited[i] = 0;

while (!q.empty())
{
int node = q.front().first;
int group = q.front().second;
q.pop();

for (auto next: graph[node])
{

if (visited[next]!=-1)
{
if (visited[next]!=1-group)
return false;
}
else
{
visited[next] = 1-group;
q.push({next, 1-group});
}
}
}
}

return true;
}
};

0 comments on commit 14c9e15

Please sign in to comment.