Given an undirected graph, return true if and only if it is bipartite.
Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.
The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice.
Example 1:
Input: [[1,3], [0,2], [1,3], [0,2]]
Output: true
Explanation:
The graph looks like this:
0----1
| |
| |
3----2
We can divide the vertices into two groups: {0, 2} and {1, 3}.
Example 2: Input: [[1,2,3], [0,2], [0,1,3], [0,2]] Output: false Explanation: The graph looks like this: 0----1 | \ | | \ | 3----2 We cannot find a way to divide the set of nodes into two independent subsets.
Note:
graphwill have length in range[1, 100].graph[i]will contain integers in range[0, graph.length - 1].graph[i]will not containior duplicate values.- The graph is undirected: if any element
jis ingraph[i], theniwill be ingraph[j].
Related Topics:
Depth-first Search, Breadth-first Search, Graph
// OJ: https://leetcode.com/problems/is-graph-bipartite/
// Author: github.com/lzl124631x
// Time: O(V + E)
// Space: O(V + E)
class Solution {
bool dfs(vector<vector<int>> &G, vector<int> &id, int u, int prev = 1) {
if (id[u]) return id[u] != prev;
id[u] = -prev;
for (int v : G[u]) {
if (!dfs(G, id, v, id[u])) return false;
}
return true;
}
public:
bool isBipartite(vector<vector<int>>& G) {
vector<int> id(G.size());
for (int i = 0; i < G.size(); ++i) {
if (id[i]) continue;
if (!dfs(G, id, i)) return false;
}
return true;
}
};// OJ: https://leetcode.com/problems/is-graph-bipartite/
// Author: github.com/lzl124631x
// Time: O(V + E)
// Space: O(V + E)
class Solution {
public:
bool isBipartite(vector<vector<int>>& G) {
vector<int> id(G.size());
queue<int> q;
for (int i = 0; i < G.size(); ++i) {
if (id[i]) continue;
q.push(i);
id[i] = 1;
while (q.size()) {
int u = q.front();
q.pop();
for (int v : G[u]) {
if (id[v]) {
if (id[v] != -id[u]) return false;
continue;
}
id[v] = -id[u];
q.push(v);
}
}
}
return true;
}
};