[LeetCode] 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] 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:
graphwill have length in range[1, 100].graph[i]will contain integers in range[0, graph.length - 1].graph[i]will not containior duplicate values.- The graph is undirected: if any element
jis ingraph[i], theniwill be ingraph[j].
这道题博主在最开始做的时候,看了半天,愣是没弄懂输出数据的意思,博主开始以为给的是边,后来发现跟图对应不上,就懵逼了,后来是通过研究论坛上大神们的解法,才总算搞懂了题目的意思,原来输入数组中的 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:
bool isBipartite(vector<vector<int>>& graph) {
vector<int> colors(graph.size());
for (int i = ; i < graph.size(); ++i) {
if (colors[i] == && !valid(graph, , i, colors)) {
return false;
}
}
return true;
}
bool valid(vector<vector<int>>& graph, int color, int cur, vector<int>& colors) {
if (colors[cur] != ) return colors[cur] == color;
colors[cur] = color;
for (int i : graph[cur]) {
if (!valid(graph, - * color, i, colors)) {
return false;
}
}
return true;
}
};
我们再来看一种迭代的解法,整体思路还是一样的,还是遍历整个顶点,如果未被染色,则先染色为1,然后使用 BFS 进行遍历,将当前顶点放入队列 queue 中,然后 while 循环 queue 不为空,取出队首元素,遍历其所有相邻的顶点,如果相邻顶点未被染色,则染成和当前顶点相反的颜色,然后把相邻顶点加入 queue 中,否则如果当前顶点和相邻顶点颜色相同,直接返回 false,循环退出后返回 true,参见代码如下:
解法二:
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
vector<int> colors(graph.size());
for (int i = ; i < graph.size(); ++i) {
if (colors[i] != ) continue;
colors[i] = ;
queue<int> q{{i}};
while (!q.empty()) {
int t = q.front(); q.pop();
for (auto a : graph[t]) {
if (colors[a] == colors[t]) return false;
if (colors[a] == ) {
colors[a] = - * colors[t];
q.push(a);
}
}
}
}
return true;
}
};
其实这道题还可以使用并查集 Union Find 来做,所谓的并查集,简单来说,就是归类,将同一集合的元素放在一起。我们开始遍历所有结点,若当前结点没有邻接结点,直接跳过。否则就要开始进行处理了,并查集方法的核心就两步,合并跟查询。我们首先进行查询操作,对当前结点和其第一个邻接结点分别调用 find 函数,如果其返回值相同,则意味着其属于同一个集合了,这是不合题意的,直接返回 false。否则我们继续遍历其他的邻接结点,对于每一个新的邻接结点,我们都调用 find 函数,还是判断若返回值跟原结点的相同,return false。否则就要进行合并操作了,根据敌人的敌人就是朋友的原则,所有的邻接结点之间应该属于同一个组,因为就两个组,我所有不爽的人都不能跟我在一个组,那么他们所有人只能都在另一个组,所以需要将他们都合并起来,合并的时候不管是用 root[parent] = y 还是 root[g[i][j]] = y 都是可以,因为不管直接跟某个结点合并,或者跟其祖宗合并,最终经过 find 函数追踪溯源都会返回相同的值,参见代码如下:
解法三:
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
vector<int> root(graph.size());
for (int i = ; i < graph.size(); ++i) root[i] = i;
for (int i = ; i < graph.size(); ++i) {
if (graph[i].empty()) continue;
int x = find(root, i), y = find(root, graph[i][]);
if (x == y) return false;
for (int j = ; j < graph[i].size(); ++j) {
int parent = find(root, graph[i][j]);
if (x == parent) return false;
root[parent] = y;
}
}
return true;
}
int find(vector<int>& root, int i) {
return root[i] == i ? i : find(root, root[i]);
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/785
类似题目:
参考资料:
https://leetcode.com/problems/is-graph-bipartite/
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Is Graph Bipartite? 是二分图么?的更多相关文章
- [LeetCode] 785. Is Graph Bipartite? 是二分图么?
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- LeetCode - Is Graph Bipartite?
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- [leetcode]785. Is Graph Bipartite? [bai'pɑrtait] 判断二分图
Given an undirected graph, return true if and only if it is bipartite. Example 1: Input: [[1,3], [0, ...
- 【LeetCode】785. Is Graph Bipartite? 解题报告(Python)
[LeetCode]785. Is Graph Bipartite? 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu. ...
- [LeetCode] Possible Bipartition 可能的二分图
Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of ...
- [Swift]LeetCode785. 判断二分图 | Is Graph Bipartite?
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- LeetCode 785. Is Graph Bipartite?
原题链接在这里:https://leetcode.com/problems/is-graph-bipartite/ 题目: Given an undirected graph, return true ...
- [LeetCode] 785. Is Graph Bipartite?_Medium tag: DFS, BFS
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- Edge coloring of bipartite graph CodeForces - 600F (二分图染色)
大意:给定二分图, 求将边染色, 使得任意邻接边不同色且使用颜色种类数最少 最少颜色数即为最大度数, 要输出方案的话, 对于每一条边(u,v), 求出u,v能使用的最小的颜色$t0$,$t1$ 若t0 ...
随机推荐
- [poj3280]Cheapest Palindrome_区间dp
Cheapest Palindrome poj-3280 题目大意:给出一个字符串,以及每种字符的加入代价和删除代价,求将这个字符串通过删减元素变成回文字符串的最小代价. 注释:每种字符都是小写英文字 ...
- 优化的四个方面,缓存,表结构,索引,SQL语句
一,缓存 数据库属于 IO 密集型的应用程序,其主要职责就是数据的管理及存储工作.而我们知道,从内存中读取一个数据库的时间是微秒级别,而从一块普通硬盘上读取一个IO是在毫秒级别,二者相差3个数量级.所 ...
- java基础笔记(10)----集合之set集合
set接口特点: 存储任意Object元素 无序,无下标,元素内容不可以重 方法: 继承父接口Collection中的所有方法 遍历: 有两种遍历方法,foreach遍历和迭代遍历 forEach遍历 ...
- 以太坊开发DApp实战教程——用区块链、星际文件系统(IPFS)、Node.js和MongoDB来构建电商平台(一)
第一节 简介 欢迎和我们一起来用以太坊开发构建一个去中心化电商DApp!我们将用区块链.星际文件系统(IPFS).Node.js和MongoDB来构建电商平台类似淘宝的在线电商应用,卖家可以自由地出售 ...
- java 5线程中 Semaphore信号灯,CyclicBarrier类,CountDownLatch计数器以及Exchanger类使用
先来讲解一下Semaphore信号灯的作用: 可以维护当前访问自身的线程个数,并提供了同步机制, 使用semaphore可以控制同时访问资源的线程个数 例如,实现一个文件允许的并发访问数. 请看下面 ...
- C语言函函数嵌套
一.实验作业 1.1 PTA题目 设计思路 1.定义整形变量i,if(b==n-1)用于递归的终止,并返回1. 2.for i=b to n ,if(a[i]<a[min]);进行升序排序 3. ...
- 关于DLL的创建与使用简单描述(C++、C#)
前言 前一段时间在学关于DLL的创建与调用,结果发现网络上一大堆别人分享的经验都有点问题.现在整理分享一下自己的方法. 工具 Microsoft Visual Studio 2017 depends ...
- 项目Alpha冲刺Day5
一.会议照片 二.项目进展 1.今日安排 熟悉后台框架并尝试编写及继续搭建前台框架模版.完成登录相关的功能实现,添加一些用户相关的单元测试代码,以及相应的测试数据. 2.问题困难 前端不是很熟,页面框 ...
- HTML5的新的结构元素介绍
HTML5的新的结构元素介绍 一.HTML5与HTML4的区别 1. 取消了一些过时的HTML4的标签 其中包括纯粹显示效果的标记,如<font>和<center>,它们已经被 ...
- python3爬虫之入门和正则表达式
前面的python3入门系列基本上也对python入了门,从这章起就开始介绍下python的爬虫教程,拿出来给大家分享:爬虫说的简单,就是去抓取网路的数据进行分析处理:这章主要入门,了解几个爬虫的小测 ...