Possible Bipartition

Given a set ofN people (numbered1, 2, ..., N), we would like to split everyone into two groups ofanysize.

Each person may dislike some other people, and they should not go into the same group.

Formally, ifdislikes[i] = [a, b], it means it is not allowed to put the people numberedaandbinto the same group.

Returntrue if and only if it is possible to split everyone into two groups in this way.

  1. 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:

Note:

分析

和以往visit直接返回不同,这里visit的话就判断对错返回,否则继续bfs或者dfs

color既记录颜色(0,1),也当做seen用。每次dfs比较颜色,不对就返错。记得main里要loop 防止没有遍历过的人。

bfs:

union find

每次u和neighbor v 比较,一个爹就错,然后把所有Neighbor都Union。

Last updated

Was this helpful?