题目
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.
算法思路
输入:用二维数组表示的一个无向图
输出:判断这个图是否为二分图
这周学习深度优先搜索法在图论研究中的应用,这道题就是很好的一道练习题。根据二分图的性质可知需要存在一个两个子集的划分,任意一条边的两个顶点不在同一个子集。
考虑用深度优先搜索法(DFS),对节点涂双色解决,从一个初始点涂1出发,每到一个节点,检查与此节点有关的边的对应点
- 如果对应点没被涂色,则涂上与正在检查的点相反的颜色。
- 如果对应点已被涂色,则判断此边的两点颜色是否相同,相同则违反二分图定义,不是二分图,否则继续。
最后所有节点涂上颜色没有违反二分图定义,则是二分图。
需要注意的是如果存在多个连通分支,DFS递归函数执行完时并没有检查完所有节点,需要在未检查的点中再选一个初始点执行DFS递归,否则判断会出错。
C++代码
class Solution {
public:
//深度搜索的递归实现
bool helper(vector<vector<int>>& graph, int node, int state[]) {
for (int i = 0; i < graph[node].size(); ++i) {
if (state[graph[node][i]] == 0) {
state[graph[node][i]] = 3 - state[node];
if (helper(graph, graph[node][i], state) == false)
{
return false;
}
}
else if (state[graph[node][i]] == state[node]) {
return false;
}
}
return true;
}
bool isBipartite(vector<vector<int>>& graph) {
int state[graph.size()] = {0};
for (int i = 0; i < graph.size(); ++i)
{
if (state[i] == 0)
{
state[i] = 1;
if (helper(graph, i, state) == false)
{
return false;
}
}
}
return true;
}
};