Fork me on GitHub

Is Graph Bipartite?

Description

https://leetcode.com/problems/is-graph-bipartite/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
int size = graph.size();
if (size == 1) return true;
vector<int> colors(size, 0);

for (int i = 0; i < size; ++i) {
if (colors[i] != 0) continue;
if (dfs(i, colors, graph, 1) == false) return false;
}
return true;
}

bool dfs(int index, vector<int>& colors, vector<vector<int>>& graph, int color) {
if (colors[index] != 0) return colors[index] == color;
colors[index] = color;
vector<int>& near = graph[index];
for (int item : near) {
if (dfs(item, colors, graph, -color) == false) return false;
}
return true;
}
};