1
+ /*
2
+
3
+ 附上大佬的参考代码
4
+ https://leetcode.com/problems/is-graph-bipartite/discuss/115487/Java-Clean-DFS-solution-with-Explanation
5
+
6
+ u 代表还没有被上色
7
+ r 表示红色
8
+ b 表示蓝色
9
+ */
10
+
11
+ // 单纯使用简单的DFS的代码有点超时,还需要再优化一下
12
+ // 63 / 78 test cases passed.
13
+ class Solution
14
+ {
15
+ public:
16
+ bool isBipartite (vector<vector<int >>& graph)
17
+ {
18
+ if (graph.size () == 0 ) return true ;
19
+
20
+ vector<char > memo (graph.size (), ' u' );
21
+
22
+ return safe (graph, memo, 0 );
23
+ }
24
+ private:
25
+ bool safe (const vector<vector<int >>& graph, vector<char >& memo, int startIndex)
26
+ {
27
+ // 递归停止条件
28
+ if (startIndex == graph.size ()) return true ;
29
+
30
+ if (memo[startIndex] != ' u' )
31
+ {
32
+ for (auto node : graph[startIndex])
33
+ {
34
+ if (memo[node] == memo[startIndex]) return false ;
35
+ }
36
+
37
+ char color = memo[startIndex] == ' b' ? ' r' : ' b' ;
38
+ for (auto node : graph[startIndex])
39
+ {
40
+ memo[node] = color;
41
+ }
42
+
43
+ return safe (graph, memo, startIndex + 1 );
44
+ }
45
+ else
46
+ {
47
+ vector<char > tempmemo = memo;
48
+
49
+ vector<char > colors = {' b' , ' r' };
50
+ for (char color : colors)
51
+ {
52
+ memo[startIndex] = color;
53
+
54
+ bool bad = false ;
55
+ for (auto node : graph[startIndex])
56
+ {
57
+ if (memo[node] == memo[startIndex])
58
+ {
59
+ bad = true ;
60
+ break ;
61
+ }
62
+ }
63
+
64
+ if (bad) continue ;
65
+
66
+ char tempcolor = memo[startIndex] == ' b' ? ' r' : ' b' ;
67
+ for (auto node : graph[startIndex])
68
+ {
69
+ memo[node] = tempcolor;
70
+ }
71
+
72
+ if (safe (graph, memo, startIndex + 1 ))
73
+ return true ;
74
+ else
75
+ memo = tempmemo;
76
+ }
77
+
78
+ memo[startIndex] = ' u' ;
79
+ return false ;
80
+ }
81
+ }
82
+ };
83
+
84
+ // 充分理解题目意思之后的BFS改进代码
85
+ // Runtime: 44 ms, faster than 7.69% of C++ online submissions for Is Graph Bipartite?.
86
+ // Memory Usage: 11.9 MB, less than 38.46% of C++ online submissions for Is Graph Bipartite?.
87
+ class Solution
88
+ {
89
+ public:
90
+ bool isBipartite (vector<vector<int >>& graph)
91
+ {
92
+ vector<char > memo (graph.size (), ' u' );
93
+
94
+ for (int index = 0 ; index < memo.size (); ++index )
95
+ {
96
+ if (memo[index ] != ' u' ) continue ;
97
+
98
+ queue<int > q;
99
+ int layer = 1 ;
100
+ q.push (index );
101
+
102
+ while (!q.empty ())
103
+ {
104
+ for (int i = q.size (); i > 0 ; --i)
105
+ {
106
+ int node = q.front ();
107
+ memo[node] = layer % 2 == 0 ? ' r' : ' b' ;
108
+ q.pop ();
109
+
110
+ for (auto nextNode : graph[node])
111
+ {
112
+ if (memo[node] == memo[nextNode]) return false ;
113
+ }
114
+
115
+ for (auto nextNode : graph[node])
116
+ {
117
+ if (memo[nextNode] == ' u' ) q.push (nextNode);
118
+ }
119
+ }
120
+ ++layer;
121
+ }
122
+ }
123
+ return true ;
124
+ }
125
+ };
0 commit comments