[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 ...
随机推荐
- Qt编写机房安全作业预警系统
最近给一个朋友做了个项目,运行在一个日本大型企业中,大屏显示.机房安全作业预警系统工事主要是由监控系统和报警系统组成.其目的就是通过监控系统实时观察空压机房内的动态,通过报警系统确认空压机房在规定的时 ...
- python tkinter教程-事件绑定
一个Tkinter主要跑在mainloop进程里.Events可能来自多个地方,比如按键,鼠标,或是系统事件. Tkinter提供了丰富的方法来处理这些事件.对于每一个控件Widget,你都可以为其绑 ...
- gradle项目,连同依赖一起打jar包
在build里加入以下配置(如果不是一个可执行的jar包的话就不用配置Main-Class属性): def mainClassName = "你需要执行的main方法所在的的包名+类名&qu ...
- 圆形CD绘制 (扇形)
参考: Egret教程Arc是使用示例:http://edn.egret.com/cn/article/index/id/673 我封装的工具类: /** * 圆形进度 * @author chenk ...
- 微信小游戏 交互接口的使用 wx.showToast wx.showLoading
在小游戏中,会有如下图的提示窗口,这些可以使用微信提供的交互接口实现. 使用loading等待的接口.mask=true表示遮罩,防止等待时点击其他按钮触发其他操作导致异常. wx.showLoadi ...
- Ios8 Xcode6 设置Launch Image 启动图片
http://blog.sina.com.cn/s/blog_6c97abf10102voui.html Http://Www.woowen.com/Swift/2014/12/12/Ios8设置La ...
- python添加Windows环境变量
1.cmd中添加方式 SET PATH=%PATH%;c:\Program Files (x86)\Wireshark 注:如上代码添加c:\Program Files (x86)\Wireshark ...
- yii---对数组进行分页
很多时候,我们会对多个数据进行分页处理,例如我最近开发的一个功能,系统消息,系统消息的来源是多个表,而且多个表之间的数据没有任何关联,这个时候,需要对多个表进行查询,查询返回的数据进行分页,而且采用的 ...
- HTTP协议的前世今生——各版本HTTP协议对比
HTTP协议是如今互联网与服务端技术的基石,HTTP协议的演进也从侧面反应了互联网技术的快速发展.这两天在准备一次关于HTTP1.1协议特性的技术分享过程中,顺便了解了下各版本HTTP协议的特点,在这 ...
- Numpy基础学习与总结
Numpy类型学习 1.数组的表示 import numpy as np In [2]: #numpy核心是高维数组,库中的ndarray支持多维数组,同时提供了数值运算,可对向量矩阵进行运算 In ...