[leetcode]886. Possible Bipartition
Analysis
Still raining outside…—— [每天刷题并不难0.0]
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.
Explanation:
Solved by DFS,
- group[i] = 0 means node i hasn’t been visited.
- group[i] = 1 means node i has been grouped to 1.
- group[i] = -1 means node i has been grouped to -1.
Implement
class Solution {
public:
bool possibleBipartition(int N, vector<vector<int>>& dislikes) {
vector<vector<int>> graph(N, vector<int>(N));
for(vector<int> d:dislikes){
graph[d[0]-1][d[1]-1] = 1;
graph[d[1]-1][d[0]-1] = 1;
}
vector<int> group(N, 0);
for(int i=0; i<N; i++){
if(group[i]==0 && !DFS(N, graph, group, i, 1))
return false;
}
return true;
}
bool DFS(int N, vector<vector<int>>& graph, vector<int>& group, int idx, int g){
group[idx] = g;
for(int i=0; i<N; i++){
if(graph[idx][i] == 1){
if(group[i] == g)
return false;
if(group[i] == 0 && !DFS(N, graph, group, i, -g))
return false;
}
}
return true;
}
};