886. 可能的二分法
难度:中等
题目描述
解题思路
跟今天的打卡题差不多,就是要先自己建图,然后用染色的思想进行BFS或者DFS
1、DFS
public boolean possibleBipartition(int N, int[][] dislikes) {
ArrayList<Integer>[] graph = new ArrayList[N+1];
for (int i = 0; i < N + 1; i++) { //先建图
graph[i] = new ArrayList<>();
}
for (int[] dislike : dislikes) {
int a = dislike[0];
int b = dislike[1];
graph[a].add(b);
graph[b].add(a);
}
int[] color = new int[N+1]; //0没分组,1,-1
for (int i = 1; i <= N; i++) {
if(color[i] == 0) { //如果还没分组,加入到队列里
if(!dfspossibleBipartition(graph, color, i, 1))
return false;
}
}
return true;
}
public boolean dfspossibleBipartition(ArrayList<Integer>[] graph,int[] color,int a,int target) {
color[a] = target;
ArrayList<Integer> dislike = graph[a]; //获取a不喜欢的人名单
if(dislike == null) //可能没有不喜欢的人
return true;
for (int i = 0; i < dislike.size(); i++) {
int b = dislike.get(i);
System.out.println(b);
if(color[b] == 0) {
if(!dfspossibleBipartition(graph, color, b, -target)) {
return false;
}
}else if(color[b] == target) {
return false;
}
}
return true;
}
2、BFS
public boolean possibleBipartition1(int N, int[][] dislikes) {
ArrayList<Integer>[] graph = new ArrayList[N+1];
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < N + 1; i++) { //先建图
graph[i] = new ArrayList<>();
}
for (int[] dislike : dislikes) {
int a = dislike[0];
int b = dislike[1];
graph[a].add(b);
graph[b].add(a);
}
int[] color = new int[N+1]; //0没分组,1,-1
for (int i = 1; i <= N; i++) {
if(color[i] == 0) { //如果还没分组,加入到队列里
color[i] = 1;
queue.add(i);
while(!queue.isEmpty()) {
int a = queue.poll();
for (int j = 0; j < graph[a].size(); j++) {
int b = graph[a].get(j);
if(color[b] == 0) {
color[b] = -color[a];
queue.add(b);
}else if(color[b] == color[a]) {
return false;
}
}
}
}
}
return true;
}