class Solution { int[] color; Map<Integer,List<Integer>> map; public boolean possibleBipartition(int N, int[][] dislikes) { map = new HashMap<>(); color = new int[N+1]; for(int[] d : dislikes) { map.computeIfAbsent(d[0],k->new ArrayList<>()).add(d[1]); map.computeIfAbsent(d[1],k->new ArrayList<>()).add(d[0]); } for(int i = 1; i <= N; i++) { // 每个点都要出发进行dfs染色 if(color[i] != 0) continue; if(!dfs(i,1)) return false; // 染成1 2两种颜色 } return true; } public boolean dfs(int u, int c) { color[u] = c; if(!map.containsKey(u)) return true; for(int k : map.get(u)) { if(color[k] != 0) { if(color[k] == c) { return false; } } else { if(!dfs(k,3-c)) return false; } } return true; } }