-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisBipartite_785.h
97 lines (82 loc) · 2.72 KB
/
isBipartite_785.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// Created by so_go on 2020/7/16.
//
/*
* 785. 判断二分图
给定一个无向图graph,当这个图为二分图时返回true。
如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。
graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。
示例 1:
输入: [[1,3], [0,2], [1,3], [0,2]]
输出: true
解释:
无向图如下:
0----1
| |
| |
3----2
我们可以将节点分成两组: {0, 2} 和 {1, 3}。
示例 2:
输入: [[1,2,3], [0,2], [0,1,3], [0,2]]
输出: false
解释:
无向图如下:
0----1
| \ |
| \ |
3----2
我们不能将节点分割成两个独立的子集。
注意:
graph 的长度范围为 [1, 100]。
graph[i] 中的元素的范围为 [0, graph.length - 1]。
graph[i] 不会包含 i 或者有重复的值。
图是无向的: 如果j 在 graph[i]里边, 那么 i 也会在 graph[j]里边。
*/
#ifndef SRC_ISBIPARTITE_785_H
#define SRC_ISBIPARTITE_785_H
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
unordered_set<int> A, B;
vector<int> tA, tB;
int count = 0;
vector<bool> isVisit(graph.size(), false);
for(int i = 0; i < graph.size(); ++i){
if(not isVisit[i]){
tA = {i};
while(tA.size() > 0){
tB.clear();
for(int a: tA){
if(A.find(a) == A.end()) {
if(B.find(a) != B.end()){
return false;
}
for (int b: graph[a]) {
tB.push_back(b);
}
A.insert(a);
count++;
}
}
tA.clear();
for(int b: tB){
if(B.find(b) == B.end()){
if(A.find(b) != A.end()){
return false;
}
for(int a: graph[b]) {
tA.push_back(a);
}
B.insert(b);
count++;
}
}
}
}
}
return false;
}
};
#endif //SRC_ISBIPARTITE_785_H