886. Possible Bipartition

```java
class Solution {
    public boolean possibleBipartition(int n, int[][] dislikes) {
        Map<Integer, List<Integer>> graph = buildGraph(dislikes);
        int[] color = new int[n+1]; // 0, 1, -1
        for (int i = 1; i <= n; i++) {
            if (color[i] == 0) {
                if (!dfs(graph, color, i, 1)) {
                    return false;
                }
            }
        }
        return true;
    }
    
    private boolean dfs(Map<Integer, List<Integer>> graph, int[] color, int currNode, int wantedColor) {
        if (color[currNode] != 0) {
            return color[currNode] == wantedColor;
        }
        color[currNode] = wantedColor;

        if (graph.containsKey(currNode)) {
            for (int next : graph.get(currNode)) {
                if (!dfs(graph, color, next, wantedColor*(-1))) {
                    return false;
                }
            }
        }
        return true;
    }

    private Map<Integer, List<Integer>> buildGraph(int[][] dislikes) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int[] dislike : dislikes) {
            graph.putIfAbsent(dislike[0], new ArrayList<>());
            graph.get(dislike[0]).add(dislike[1]);

            graph.putIfAbsent(dislike[1], new ArrayList<>());
            graph.get(dislike[1]).add(dislike[0]);
        }
        return graph;
    }
}


```

Last updated