Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false
Example 3:
Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
Output: false
Constraints:
1 <= N <= 2000
0 <= dislikes.length <= 10000
dislikes[i].length == 2
1 <= dislikes[i][j] <= N
dislikes[i][0] < dislikes[i][1]
There does not exist i != j for which dislikes[i] == dislikes[j].
classSolution {// Color -> 0 not colored YET// Color -> 1 (one of the colors)// Color -> -1 (The other color)// colors array works as color storage as well as visited arrayint[] colors;List<Integer>[] graph;publicbooleanpossibleBipartition(int N,int[][] dislikes) {// Creating adjacency list graph graph =newArrayList[N];for (int i =0; i < N; i++) graph[i] =newArrayList<>();for (int[] pair : dislikes) { graph[pair[0] -1].add(pair[1] -1); graph[pair[1] -1].add(pair[0] -1); } colors =newint[N];for (int i =0; i < N; i++)if (colors[i] ==0&&!paint(i,1))returnfalse;returntrue; }booleanpaint(int u,int color) {// "color" -> the color we want this person ("u") to beif (colors[u] !=0)return colors[u] == color; colors[u] = color;for (int neighbor : graph[u])// If we cannot paint the neighbor with opposite colorif (!paint(neighbor,-color))returnfalse;returntrue; }}