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.

  

原来输入数组中的graph[i],表示顶点i所有相邻的顶点,比如对于例子1来说,顶点0和顶点1,3相连,顶点1和顶点0,2相连,顶点2和结点1,3相连,顶点3和顶点0,2相连。这道题让我们验证给定的图是否是二分图,所谓二分图,就是可以将图中的所有顶点分成两个不相交的集合,使得同一个集合的顶点不相连。为了验证是否有这样的两个不相交的集合存在,我们采用一种很机智的染色法,大体上的思路是要将相连的两个顶点染成不同的颜色,一旦在染的过程中发现有两连的两个顶点已经被染成相同的颜色,说明不是二分图。这里我们使用两种颜色,分别用1和-1来表示,初始时每个顶点用0表示未染色,然后遍历每一个顶点,如果该顶点未被访问过,则调用递归函数,如果返回false,那么说明不是二分图,则直接返回false。如果循环退出后没有返回false,则返回true。在递归函数中,如果当前顶点已经染色,如果该顶点的颜色和将要染的颜色相同,则返回true,否则返回false。如果没被染色,则将当前顶点染色,然后再遍历与该顶点相连的所有的顶点,调用递归函数,如果返回false了,则当前递归函数的返回false,循环结束返回true,参见代码如下:

class Solution {
public boolean isBipartite(int[][] graph) {
if(graph == null){
return false;
}
int v = graph.length;
//if we only have 2 vertices, then it's a Bipartite
if(v <= 2){
return true;
}
int[] colors = new int[v];
for(int i = 0; i < v; i++){
if(colors[i] == 0 && !valid(graph, i, 1, colors)){
return false;
}
}
return true;
} private boolean valid (int[][] graph, int cur, int color, int[] colors){
if(colors[cur] != 0){
return colors[cur] == color;
}
colors[cur] = color;
for(int i : graph[cur]){
if(!valid(graph, i, color * -1, colors)){
return false;
}
}
return true;
}
}

最新文章

  1. 如何安装并使用hibernate tools
  2. ps教程-三分钟画齿轮
  3. 安装XCode导致mac无法正常开机怎么办
  4. [Data Structure] 二叉搜索树(Binary Search Tree) - 笔记
  5. Trapping Raining Water 解答
  6. 使用diff和patch指令生成文件差异和还原文件
  7. Django 缓存系统
  8. popupwindow那些坑
  9. Pytorch学习笔记(一)---- 基础语法
  10. 在Linux命令行中以图形化窗口打开文件夹
  11. 利用Crosstool-ng制作交叉编译工具链
  12. c# 导入导出excel方法封装
  13. [UI] 06 - jQuery
  14. 1.Anaconda安装Tensorflow报错UnicodeDecodeError: &#39;utf-8&#39; codec can&#39;t decode ## invalid start byte的问题之解决
  15. PHP代码实现强制换行
  16. 直播 背景 技术体系 乐视云直播Demo
  17. wlan接收器如何共享网络
  18. 使用SQLite删除Mac OS X 中launchpad里的快捷方式
  19. CentOS 7 systemd添加自定义系统服务
  20. cug oj 1479 Treasure Chest Lock (区间dp 思维)

热门文章

  1. 微信授权(Net Mvc)
  2. CSS(一)属性--border边框
  3. MATLAB 图片折腾4
  4. js onclick函数中传字符串参数的问题
  5. 每天CSS学习之white-space
  6. ArrayList和LinkedList有什么区别?
  7. byte[]-&gt;new String(byte[]) -&gt; getByte()引发的不一致问题
  8. js实现网页全屏切换(平滑过渡),鼠标滚动切换
  9. JS之计时器
  10. 启动apache 找不到 mbstring.dll