![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1bf65a8bbbd6a5835419e173a82f5ba0.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b960f09f159068993da0dfa3565f24c1.png)
二分图:将所有结点分成两个集合,每条边的两个顶点处于不同的集合中。或者说图中顶点分成红色和绿色的两种。一条边相连的顶点(邻居),必须不同颜色。将相同颜色的顶点划分到一个集合。如果能够实现,就是二分图。
只要相邻(一条边相连的两个)顶点,颜色一样,就不是二分图
深度优先
解题思路:时间复杂度O(
n
+
m
n+m
n+m),n是顶点个数,m是边的数量,空间复杂度O(
n
n
n),保存每个顶点的颜色信息 |
---|
- 为每个顶点上色,红色和绿色
- 如果当前顶点为红色,相邻的顶点必须是绿色
- 如果相邻的顶点已经上色,并且和当前顶点颜色相同,就不是二分图
- 也就是说,保证一条边相连顶点颜色不同,如果整个图都满足就是二分图,只要有任何一条边的两个顶点颜色相同就不是二分图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6c35123de254499d8c9f794bb0906f94.png)
class Solution {
private static final int UNCOLORED = 0;
private static final int RED = 1;
private static final int GREEN = 2;
private int[] color;
private boolean valid;
public boolean isBipartite(int[][] graph) {
int n = graph.length;
valid = true;
color = new int[n];
Arrays.fill(color, UNCOLORED);
for (int i = 0; i < n && valid; ++i) {
if (color[i] == UNCOLORED) {
dfs(i, RED, graph);
}
}
return valid;
}
public void dfs(int node, int c, int[][] graph) {
color[node] = c;
int cNei = c == RED ? GREEN : RED;
for (int neighbor : graph[node]) {
if (color[neighbor] == UNCOLORED) {
dfs(neighbor, cNei, graph);
if (!valid) {
return;
}
} else if (color[neighbor] != cNei) {
valid = false;
return;
}
}
}
}
广度优先
解题思路:时间复杂度O(
n
+
m
n+m
n+m),n是顶点个数,m是边的数量,空间复杂度O(
n
n
n),保存每个顶点的颜色信息 |
---|
- 将深度优先改为广度优先即可
- 但是因为使用了队列,根本上还是和深度优先一样的逻辑。肯定没有深度优先遍历直接底层用系统的栈空间快
- 实际工作场景的差别不大,但是做题嘛,1ms都能拉开很大差距。所以能深度优先深度优先遍历
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/44bd5c16648ee8f277c694b4fffe10c9.png)
class Solution {
private static final int UNCOLORED = 0;
private static final int RED = 1;
private static final int GREEN = 2;
private int[] color;
public boolean isBipartite(int[][] graph) {
int n = graph.length;
color = new int[n];
for (int i = 0; i < n; ++i) {
if (color[i] == UNCOLORED) {
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(i);
color[i] = RED;
while (!queue.isEmpty()) {
int node = queue.poll();
int cNei = color[node] == RED ? GREEN : RED;
for (int neighbor : graph[node]) {
if (color[neighbor] == UNCOLORED) {
queue.offer(neighbor);
color[neighbor] = cNei;
} else if (color[neighbor] != cNei) {
return false;
}
}
}
}
}
return true;
}
}