[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 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]
.
这个题目实际意思就是说可不可以用两种颜色将graph都涂上颜色. 最初的想法是BFS, 我的前提假设是给的这个graph的所有元素都是连通的, 然后将0放入, 接着BFS遍历遍历的点, 如果点的neighbor没有visited过的, 就将neighbor设为跟点不一样的颜色, 并append进入queue, 如果visited过, 看颜色是否跟点一样,如果一样,return False.
但是提交之后发现有的test case不行, 因为给的graph允许一些单独的点存在, 也就是说不一定所有的点都要连通, 那么我初始化的时候就把0 - n-1 个点都append进入queue里面, 但是发现如果用BFS的话, 我们在初始化每个点的时候有可能之前的路径还没走完, 所以需要用DFS, 思路跟以上BFS类似, 只是把stack初始化的时候把0 - n-1个点都append进去.
updated:
我们还是用DFS, 但是除了单纯的把0 - n-1个点都append进入stack里面, 我们可以用一个dictionary去找看如果还有点不在里面的, 我们就DFS遍历一遍.跟之前类似的判断.
1. Constraints
1) size of graph [1,100]
2) graph[i] size [0,graph size -1] and no duplicates
3) undirected
4) very important! no need to connect with every node!
2. Ideas
DFS T: O(n) S: O(n)
1) 空dictionary , d
2) for i in range(len(graph)), 如果不在d里面, 将d[i] = 1, 用DFS, 将所有neigbor设为-1, 如果没有在d里面的, 如果在的, 监测跟d[i] 是否一样, 如果一样返回False
3) 结束for loop, 返回True
3. Code
1)
class Solution(object):
def isBipartite(self, graph):
"""
:type graph: List[List[int]]
:rtype: bool
"""
n, colorMap = len(graph), collections.Counter()
def dfs(i, color):
if colorMap[i] == color: return True
if colorMap[i] == color * (-1): return False
colorMap[i] = color
for neig in graph[i]:
if not dfs(neig, color * (-1)):
return False
return True
for i in range(n):
if colorMap[i] != 0:
continue
if not dfs(i, 1):
return False
return True
2)
class Solution:
def isBipartite(self, graph):
d = {}
for i in range(len(graph)):
if i not in d:
d[i] = 1
stack = [i]
while stack:
node = stack.pop()
for each in graph[node]:
if each not in d:
d[each] = d[node]*(-1)
stack.append(each)
elif d[each] == d[node]:
return False
return True
4. Test cases
1) [[1,3], [0,2], [1,3], [0,2]] => True 2)[[1,2,3], [0,2], [0,1,3], [0,2]] => False
[LeetCode] 785. Is Graph Bipartite?_Medium tag: DFS, BFS的更多相关文章
- [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? 是二分图么?
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? 解题报告(Python)
[LeetCode]785. Is Graph Bipartite? 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu. ...
- [LeetCode] 130. Surrounded Regions_Medium tag: DFS/BFS
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A reg ...
- [LeetCode]695. 岛屿的最大面积(DFS/BFS)、200. 岛屿数量(DFS/BFS待做/并差集待做)
695. 岛屿的最大面积 题目 给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合.你可以假设二维矩阵的四个边缘都被 ...
- 785. Is Graph Bipartite?
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- [LeetCode] 437. Path Sum III_ Easy tag: DFS
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] 851. Loud and Rich_ Medium tag: DFS
In a group of N people (labelled 0, 1, 2, ..., N-1), each person has different amounts of money, and ...
随机推荐
- 【Drools-开源业务规则引擎】入门实例(含源码)
该实例转自:http://blog.csdn.net/quzishen/article/details/6163012 便于理解的应用实例1: 现在我们模拟一个应用场景:网站伴随业务产生而进行的积分发 ...
- HTML - 网页特殊字符大全(转)
原文地址请跳转:https://blog.csdn.net/Iversons/article/details/78996776
- MyBatis学习之输入输出类型
1. 传递pojo对象 Mybatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称,其中,#{}:占位符号,好处防止sql注入,${}:sql拼接符号, 简要说明 ...
- mysql架构图
整体架构图 访问控制图
- 源码包安装Python3.6
1,安装Python3.6的依赖包 # yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel r ...
- docker 镜像详解
镜像的大小不等于通过docker images 看到的每个镜像大小的合集,docker镜像采用了分层的机制.上层使用共同下层,各自不同部门构建各自的独立分层. docker的镜像通过联合文件系统(un ...
- 23种设计模式之装饰模式(Decorator)
装饰模式是一种对象结构型模式,可动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活.通过装饰模式,可以在不影响其他对象的情况下,以动态.透明的方式给单个对象添加职责 ...
- 关于virgo-tomcat-server-3.6.0.RELEASE配置文件修改说明
Virgo项目Web服务器是EclipseRT项目的一部分,是一个完全模块化的Java运行时. Virgo自身就是设计为在标准OSGi框架实现(Equinox)之上的一个OSGi bundle集合. ...
- CentOS6.5安装配置PPTP
本次安装环境为Ucloud云服务器 1,操作系统版本检查 2,安装ppp,pptp yum install -y ppp rpm -ivh http://static.ucloud.cn/pptpd- ...
- 一次使用Python连接数据库生成二维码并安装为windows服务的工作任务
最近有一个需求,在现有生产系统上的人员库中增加一个此人员关键信息的二维码,支持文字版和跳转版两种方式,与报表工具关联,可打印.以windows服务方式,定时检查,只要发现某人员没有此二维码信息,就生成 ...