Is Graph Bipartite — BFS 2-Coloring
Advertisement
Problem
Given an undirected graph, return true if it is bipartite.
Solutions
Python
from collections import deque
class Solution:
def isBipartite(self, graph: list[list[int]]) -> bool:
n=len(graph); color=[-1]*n
for i in range(n):
if color[i]!=-1: continue
q=deque([i]); color[i]=0
while q:
u=q.popleft()
for v in graph[u]:
if color[v]==-1: color[v]=1-color[u]; q.append(v)
elif color[v]==color[u]: return False
return True
C++
class Solution {
public:
bool isBipartite(vector<vector<int>>& g){
int n=g.size(); vector<int> col(n,-1);
for(int i=0;i<n;i++){
if(col[i]!=-1) continue;
queue<int> q; q.push(i); col[i]=0;
while(!q.empty()){
int u=q.front();q.pop();
for(int v:g[u]){
if(col[v]==-1){col[v]=1-col[u];q.push(v);}
else if(col[v]==col[u]) return false;
}
}
}
return true;
}
};
Complexity
- Time: O(V+E) | Space: O(V)
Advertisement