题目描述
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:
- 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]
.
解题思路
概括一下Bipartitle
的大概要求便是:将一个无向图中的节点分成两组,每一组中,组内各节点无边相连。即若有一条边e
连接节点i
和j
,那么i
和j
必须要属于不同的分组。
我们应用染色的思想,将相同组的节点染成同一种“颜色”。若遍历整个图后,可以成功的染色,则必定存在一种方法,将这个图分成两部分,且满足Bipartitle
要求,若不能染色成功,则该图不满足Bipartitle
的要求。
这里我们采用BFS遍历无向图,每遍历到一个节点,先查询该节点是否染色,若未染色,则染上和前驱节点不同的颜色;若染色,检查染色结果是否冲突,不冲突就继续遍历,否则该图不满足要求,返回false
。
Tips: 题目中没有指明该图是否一定是全连通图,所以要考虑部分节点不连通的情况。
代码:
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
vector<int> group(graph.size(), 0);
queue<int> q;
for (int i = 0; i < graph.size(); i++) {
if (group[i] != 0) continue;
q.push(i);
group[i] = 1;
while(!q.empty()) {
int front = q.front();
q.pop();
for (auto iter : graph[front]) {
if (group[iter] == 0) {
group[iter] = -group[front];
q.push(iter);
} else {
if (group[iter] != -group[front]) return false;
}
}
}
}
return true;
}
};
运行结果:
这里我们只需要遍历一遍无向图即可得到结果,所以算法效率是
,因为节点的数量不会超过100,所以该方法是可行的,从结果看,算法效率还是很高的。