A bipartite graph (or bigraph) is a graph whose vertices can be divided into two disjoint and independent sets U and V such that every edge connects a vertex in U to one in V. Vertex sets U and V are usually called the parts of the graph. Equivalently, a bipartite graph is a graph that does not contain any odd-length cycles.
DFS to jump between two parts and assign part number to nodes
Take each node in the Graph as starting point of DFS.
Assign the nodes to one of two parts, -1 and 1, in an alternating order.
If a node is already assigned to a part, once it's visited again, its part should be the same as the part of the previous node.
// OJ: https://leetcode.com/problems/is-graph-bipartite/// Author: github.com/lzl124631x// Time: O(V + E)// Space: O(V + E)classSolution {public:boolisBipartite(vector<vector<int>>& G) { vector<int>id(G.size()); function<bool(int,int)> dfs = [&](int u,int prev) {if (id[u]) returnid[u] != prev; // This node's part should be the same as the part of the previous partid[u] =-prev; // Assign nodes to one of the two parts, -1 or 1for (int v :G[u]) {if (!dfs(v,id[u])) returnfalse; }returntrue; };for (int i =0; i <G.size(); ++i) {if (id[i]) continue; // This node is already assigned to a partif (!dfs(i,1)) returnfalse; }returntrue; }};
BFS
Take each node in the Graph as starting point of BFS.
Assign nodes to part -1 or 1 layer by layer in an alternating order.
If a node is already assigned to a part, once it's visited again, its part should be the same as the part of the previous node.
// OJ: https://leetcode.com/problems/is-graph-bipartite/// Author: github.com/lzl124631x// Time: O(V + E)// Space: O(V + E)classSolution {public:boolisBipartite(vector<vector<int>>& G) { vector<int>id(G.size()); queue<int> q;for (int i =0; i <G.size(); ++i) {if (id[i]) continue; // This node is already assigned to a partq.push(i);id[i] =1; // Assign this starting node to part 1while (q.size()) {int u =q.front();q.pop();for (int v :G[u]) {if (id[v]) {if (id[v] !=-id[u]) returnfalse; // Two neighboring nodes shouldn't be in the same partcontinue; }id[v] =-id[u]; // Assign neighbor node to the other partq.push(v); } } }returntrue; }};