[Week 3] LeetCode 785. Is Graph Bipartite?
阿新 • • 發佈:2018-12-11
LeetCode 785. Is Graph Bipartite?
問題描述:
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]
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:
graph
will have length in range[1, 100]
.graph[i]
will contain integers in range[0, graph.length - 1]
.graph[i]
will not containi
or duplicate values.- The graph is undirected: if any element
j
is ingraph[i]
, theni
will be ingraph[j]
.
題解:
判斷一個圖是否是二部圖,最常見的方法就是染色法,即先選取一個點染為任意顏色,然後遍歷這個點的邊,對其鄰點進行染色(與這個點不同的顏色),如果發現其鄰點已染色,則有兩種情況:
- 與該點同色,則說明該圖不是二部圖
- 與該點異色,則說明之前其鄰點已經遍歷過了
Ok,想法很簡單,用 BFS 或 DFS 都能簡單地完成這個任務,只是需要注意這個圖可能不是一個連通圖,所以應該從每個節點開始遍歷,避免漏掉某些節點。
Code:
/*
* 0 代表未染色,1 和 -1 表示兩種不同的顏色
*/
bool isBipartite(vector<vector<int> >& graph) {
vector<int> colorOfNode(graph.size(), 0);
for (int k = 0; k < graph.size(); ++k) {
queue<int> openList;
if (colorOfNode[k] == 0) openList.push(k);
while (!openList.empty()) {
int u = openList.front();
openList.pop();
if (colorOfNode[u] == 0) colorOfNode[u] = -1;
for (int i = 0; i < graph[u].size(); ++i) {
int v = graph[u][i];
if (colorOfNode[v] == colorOfNode[u]) return false;
else if (colorOfNode[v] == -colorOfNode[u]) continue;
else {
colorOfNode[v] = -colorOfNode[u];
openList.push(v);
}
}
}
}
return true;
}
複雜度分析:
每個節點只會被遍歷一次,然後與節點相連的邊大部分情況下都會被遍歷一次(這裡指 u->v ,因為這個圖本身是個無向圖),所以複雜度是 O(|V|+|E|)。所以這是一個線性判斷一個圖是否為二部圖的演算法。