Given an undirected graph
, return true
if and only if it is bipartite.
Example 1:
Input: [[1,3], [0,2], [1,3], [0,2]]
Output: true
Explanation:
The graph looks like this:
0----1
| |
| |
3----2
We can divide the vertices into two groups: {0, 2} and {1, 3}.
Example 2:
Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
Output: false
Explanation:
The graph looks like this:
0----1
| \ |
| \ |
3----2
We cannot find a way to divide the set of nodes into two independent subsets.
设G=(V,E)是一个无向图。如顶点集V可分割为两个互不相交的子集V1,V2之并,并且图中每条边依附的两个顶点都分别属于这两个不同的子集
思路
1. based on Graph Bipartite attribute, we can fill two different color for each subset.
2. if not Graph Bipartite, at lease one node such that its color happens to be the same as its neighbor
3. coz we need to traversal each node, we can both use dfs and bfs
代码
class Solution {
public boolean isBipartite(int[][] graph) {
int[] visited = new int[graph.length];
//default 0: not visited;
//lable 1: green
//lable 2: red
for(int i = 0; i < graph.length; i++) {
// such node has been visited
if(visited[i] != 0) {continue;}
//such node has not been visited
Queue<Integer> queue = new LinkedList();
queue.add(i);
// mark as green
visited[i] = 1;
while(!queue.isEmpty()) {
int cur = queue.poll();
int curLable = visited[cur];
// if curLable is green, fill neighborLable to red
int neighborLable = curLable == 1? 2:1;
for(int neighbor:graph[cur]) {
//such node has not been visited
if(visited[neighbor] == 0) {
visited[neighbor] = neighborLable;
queue.add(neighbor);
}
// node visited, and visited[neighbor] != neighborLable, conflict happens
else if(visited[neighbor] != neighborLable) {
return false;
}
}
}
}
return true;
}
}