[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:
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都涂上颜色. 最初的想法是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 ...
随机推荐
- 【github】添加 ssh 秘钥
1 生成秘钥 打开shell 备注: 123@example.com 为邮箱地址 ssh-keygen -t rsa -C "123@example.com" 此处选Y ,其他都是 ...
- jquery.sparkline.js简介
jQuery线状图插件Sparkline 官网地址:http://omnipotent.net/jquery.sparkline/ 文档地址:http://omnipotent.net/jquery. ...
- es6 - class的学习
http://es6.ruanyifeng.com/#docs/class:class Person { constructor{ //构造函数,里边放不被继承的私有属性和方法 this.proper ...
- SharpGL学习笔记(五) 视口变换
视口变换主是将视景体内投影的物体显示到二维的视口平面上. 在计算机图形学中,它的定义是将经过几何变换, 投影变换和裁剪变换后的物体显示于屏幕指定区域内. 前面我们讨论过的透视投影, 正射投影, 它们都 ...
- iPhone X 上删除白条
方案一:纯色背景的情况下,解决方案就是background-color在您的body代码上设置属性: 方案二:视口入,viewport-fit=cover: <meta name="v ...
- C程序设计语言习题(1-12)
统计行数.单词数,字符数的程序: #include<stdio.h> #define IN 1 /*在单词内*/ #define OUT 0 /*在单词外*/ int main() { i ...
- 使用atomic一定是线程安全的吗?
这个问题很少遇到,但是答案当然不是.atomic在set方法里加了锁,防止了多线程一直去写这个property,造成难以预计的数值.但这也只是读写的锁定.跟线程安全其实还是差一些.看下面. @inte ...
- iOS8新特性(2)——UIPopoverController和UIPresentationController
一.以往使用 UIPopoverController 都是只在iPad上使用 /** * UIPopoverController 只能用于iPad,上,iPhone上使用会崩溃 */ -(void)o ...
- 记一次centos7内核可能意外丢失(测试直接干掉)恢复方法
本次是虚拟机装的centos7的内核不知原因以外丢失造成无法开机,开机显示找不到内核! 恢复方法: 挂载新的ISO文件,然后进入bios选择dvd启动. 启动后进入Troublesshooting,然 ...
- rs.getMetadata
元数据(MetaData),即定义数据的数据.打个比方,就好像我们要想搜索一首歌(歌本身是数据),而我们可以通过歌名,作者,专辑等信息来搜索,那么这些歌名,作者,专辑等等就是这首歌的元数据.因此数据库 ...