-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIs_Graph_Bipartite.cpp
125 lines (105 loc) · 3.45 KB
/
Is_Graph_Bipartite.cpp
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
附上大佬的参考代码
https://leetcode.com/problems/is-graph-bipartite/discuss/115487/Java-Clean-DFS-solution-with-Explanation
u 代表还没有被上色
r 表示红色
b 表示蓝色
*/
// 单纯使用简单的DFS的代码有点超时,还需要再优化一下
// 63 / 78 test cases passed.
class Solution
{
public:
bool isBipartite(vector<vector<int>>& graph)
{
if (graph.size() == 0) return true;
vector<char> memo(graph.size(), 'u');
return safe(graph, memo, 0);
}
private:
bool safe(const vector<vector<int>>& graph, vector<char>& memo, int startIndex)
{
// 递归停止条件
if (startIndex == graph.size()) return true;
if (memo[startIndex] != 'u')
{
for (auto node : graph[startIndex])
{
if (memo[node] == memo[startIndex]) return false;
}
char color = memo[startIndex] == 'b' ? 'r' : 'b';
for (auto node : graph[startIndex])
{
memo[node] = color;
}
return safe(graph, memo, startIndex + 1);
}
else
{
vector<char> tempmemo = memo;
vector<char> colors = {'b', 'r'};
for (char color : colors)
{
memo[startIndex] = color;
bool bad = false;
for (auto node : graph[startIndex])
{
if (memo[node] == memo[startIndex])
{
bad = true;
break;
}
}
if (bad) continue;
char tempcolor = memo[startIndex] == 'b' ? 'r' : 'b';
for (auto node : graph[startIndex])
{
memo[node] = tempcolor;
}
if (safe(graph, memo, startIndex + 1))
return true;
else
memo = tempmemo;
}
memo[startIndex] = 'u';
return false;
}
}
};
// 充分理解题目意思之后的BFS改进代码
// Runtime: 44 ms, faster than 7.69% of C++ online submissions for Is Graph Bipartite?.
// Memory Usage: 11.9 MB, less than 38.46% of C++ online submissions for Is Graph Bipartite?.
class Solution
{
public:
bool isBipartite(vector<vector<int>>& graph)
{
vector<char> memo(graph.size(), 'u');
for (int index = 0; index < memo.size(); ++index)
{
if (memo[index] != 'u') continue;
queue<int> q;
int layer = 1;
q.push(index);
while (!q.empty())
{
for (int i = q.size(); i > 0; --i)
{
int node = q.front();
memo[node] = layer % 2 == 0 ? 'r' : 'b';
q.pop();
for (auto nextNode : graph[node])
{
if (memo[node] == memo[nextNode]) return false;
}
for (auto nextNode : graph[node])
{
if (memo[nextNode] == 'u') q.push(nextNode);
}
}
++layer;
}
}
return true;
}
};