Problems: https://leetcode.com/problems/is-graph-bipartite/
Solution1:
DFS
将相邻的点标上不同的颜色,判断依据为相邻两个node不可以颜色相同
利用stack存储邻接node
class Solution {
public boolean isBipartite(int[][] graph) {
int len = graph.length;
int[] color = new int[len];// 用数组标记node的颜色(0或1,未标色则为-1)
Arrays.fill(color, -1);
for (int start = 0; start < len; start++) {
if (color[start] == -1) {
color[start] = 0;
Stack<Integer> stack = new Stack<>();
stack.push(start);
// 将邻接node标色
while(!stack.isEmpty()) {
Integer node = stack.pop();
for(int link : graph[node]) {
if(color[link] == -1) {
color[link] = color[node] ^ 1;
stack.push(link);
} else if(color[link] == color[node]) {
return false;
}
}
}
}
}
return true;
}
}