### 题目

Given an undirected graph, return true if and only if it is bipartite.

Recall that a graph is bipartite if we can split it’s set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.

The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn’t contain any element twice.

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.


Note:

• graph will have length in range [1, 100].
• graph[i] will contain integers in range [0, graph.length - 1].
• graph[i] will not contain i or duplicate values.
• The graph is undirected: if any element j is in graph[i], then i will be in graph[j].

### 分析问题

0----1
| \  |
|  \ |
3----2


a组   b组
0 --> 1
+-> 2
+-> 3



b组   a组
1 --> 0
+-> 2



### BFS

0----1
|    |
|    |
3----2


#### 代码

• 1代表a组（黄色）
• -1代表b组（蓝色）
• 0代表未着色
class Solution {
public boolean isBipartite(int[][] graph) {
int[] groups = new int[graph.length]; // [0]: no group,  [1]: group a,  [-1]: group b
List<Integer> list = new ArrayList<>();
int group = 1; // [1]: group a,  [-1]: group b
for (int k = 0; k < graph.length; k++) { // graph can be composed of different isolated sub-graphs
if (groups[k] != 0) continue;
while (!list.isEmpty()) {
int size = list.size();
for (int i = 0; i < size; i++) {
int num = list.remove(0);
groups[num] = group;
for (int j = 0; j < graph[num].length; j++) {
int neighbor = graph[num][j];
if (groups[neighbor] == group) return false;
if (groups[neighbor] == 0) {
groups[neighbor] = -group;
}
}
}
group = -group;
}
}
return true;
}
}


### DFS

#### 代码

class Solution {
public boolean isBipartite(int[][] graph) {
localGraph = graph;
groups = new int[graph.length]; // [0]: no group, [1]: group a, [-1]: group b
int group = 1; // group a is default value
for (int i = 0; i < graph.length; i++) {
if (groups[i] != 0) continue;
if (!dfs(i, group)) return false;
}
return true;
}

private int[][] localGraph;
private int[] groups;

private boolean dfs(int node, int group) {
if (groups[node] != 0) return groups[node] == group;
groups[node] = group;
for (int i = 0; i < localGraph[node].length; i++) {
if (!dfs(localGraph[node][i], -group)) return false;
}
return true;
}
}