LeetCode 886. Possible Bipartition
原题链接在这里:https://leetcode.com/problems/possible-bipartition/
题目:
Given a set of N
people (numbered 1, 2, ..., N
), we would like to split everyone into two groups of any size.
Each person may dislike some other people, and they should not go into the same group.
Formally, if dislikes[i] = [a, b]
, it means it is not allowed to put the people numbered a
and b
into the same group.
Return true
if and only if it is possible to split everyone into two groups in this way.
Example 1:
Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: group1 [1,4], group2 [2,3]
Example 2:
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
Note:
1 <= N <= 2000
0 <= dislikes.length <= 10000
1 <= dislikes[i][j] <= N
dislikes[i][0] < dislikes[i][1]
- There does not exist
i != j
for whichdislikes[i] == dislikes[j]
.
题解:
To determine it is bipartition, we could see if we could color them into 2 different colors.
First use dislikes to construct a graph.
For the node hasn't been color before and it is in the graph, put it as one color 1, then perform BFS.
For cur polled number, if its neighbor has the same color, then return false.
Time Complexity: O(N+E). E = dislikes.length.
Space: O(N).
AC Java:
1 class Solution { 2 public boolean possibleBipartition(int N, int[][] dislikes) { 3 Map<Integer, Set<Integer>> graph = new HashMap<>(); 4 for(int [] d : dislikes){ 5 graph.putIfAbsent(d[0], new HashSet<Integer>()); 6 graph.putIfAbsent(d[1], new HashSet<Integer>()); 7 8 graph.get(d[0]).add(d[1]); 9 graph.get(d[1]).add(d[0]); 10 } 11 12 int [] color = new int[N+1]; 13 for(int i = 1; i<=N; i++){ 14 if(color[i]==0 && graph.containsKey(i)){ 15 color[i] = 1; 16 LinkedList<Integer> que = new LinkedList<>(); 17 que.add(i); 18 while(!que.isEmpty()){ 19 int cur = que.poll(); 20 for(int nei : graph.get(cur)){ 21 if(color[nei] == 0){ 22 color[nei] = -color[cur]; 23 que.add(nei); 24 }else if(color[nei] == color[cur]){ 25 return false; 26 } 27 } 28 } 29 } 30 } 31 32 return true; 33 } 34 }