题目描述:
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 contain i or duplicate values.
• The graph is undirected: if any element j is in graph[i], then i will be in graph[j].
采用着色法,如果一个点没有被着色,可以让它着一种颜色,然后让它的领接点都着相反的颜色,不断调用递归,可以让一整块连通区域全部着色,一旦有冲突就说明不能二分。
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
vector<int> colors(graph.size(),0); // 表示每个点的着色情况
for(int i=0;i<graph.size();i++)
{
if(colors[i]==0&&helper(graph,i,1,colors)==false) // 如果i没有被着色,即它没有和之前的任何点连通,那么可以让它的颜色等于1
return false;
}
return true;
}
// 递归函数,判断给一个点着某一种颜色是否可行
bool helper(vector<vector<int>>& graph, int i, int color, vector<int>& colors)
{
if(colors[i]!=0) return colors[i]==color;
colors[i]=color;
for(int j=0;j<graph[i].size();j++)
{
if(helper(graph,graph[i][j],-color,colors)==false)
return false;
}
return true;
}
};
本文介绍了一种使用递归着色法来判断无向图是否为二分图的方法。通过给未着色的节点上色,并使其相邻节点上相反颜色,可以检查图是否能被分为两个独立子集,每条边连接不同子集的节点。若出现颜色冲突,则表明图不能被二分。
481

被折叠的 条评论
为什么被折叠?



