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 contain i or duplicate values.
  • The graph is undirected: if any element j is in graph[i], then i will be in graph[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的更多相关文章

  1. [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, ...

  2. [LeetCode] 785. Is Graph Bipartite? 是二分图么?

    Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...

  3. LeetCode 785. Is Graph Bipartite?

    原题链接在这里:https://leetcode.com/problems/is-graph-bipartite/ 题目: Given an undirected graph, return true ...

  4. 【LeetCode】785. Is Graph Bipartite? 解题报告(Python)

    [LeetCode]785. Is Graph Bipartite? 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu. ...

  5. [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 ...

  6. [LeetCode]695. 岛屿的最大面积(DFS/BFS)、200. 岛屿数量(DFS/BFS待做/并差集待做)

    695. 岛屿的最大面积 题目 给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合.你可以假设二维矩阵的四个边缘都被 ...

  7. 785. Is Graph Bipartite?

    Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. Esper学习之十一:EPL语法(七)

    上一篇说到了EPL如何访问关系型数据库这种数据源,实际上别的数据源,比如:webservice.分布式缓存.非关系型数据库等等,Esper提供了统一的数据访问接口.然后今天会讲解如何创建另外一种事件类 ...

  2. 【python系列】python初识

    前言 Python是一种高层次,解释,互动性和面向对象的脚本语言,Python被设计成具有很强的可读性语言.它采用应用关键字,而其他语言一般使用标点符号,并且具有比其他语言有较少的语法结构. Pyth ...

  3. JUnit —— TestSuite 的使用

    首先说一下,suite ,中文是 一套,一组 的意思. 那么,TestSuite,顾名思义,就是用来运行一组测试的. 如何使用呢 ? 假设有个这样的测试类 StudentDAOTest ,代码如下: ...

  4. telnet命令的使用方法

    大家都知道,Telnet协议是TCP/IP协议族中的一员,是Internet远程登陆服务的标准协议和主要方式.它为用户提供了在本地计算机上完成远程主机工作的能力.在终端使用者的电脑上使用telnet程 ...

  5. vscode的vetur插件提示 [vue-language-server] Elements in iteration expect to have 'v-bind:key' directives错误的解决办法

    1.使用VS Code 出现如下问题,如图 Vue 2.2.0+的版本里,当在组件中使用v-for时,key是必须的. 2.更改vetur配置 vscode->文件->首选项->用户 ...

  6. iOS计算两个时间的时间差

    + (long)calculteHourL:(NSDate *)endDate startDate:(NSDate *)startDate { NSCalendar *cal = [NSCalenda ...

  7. oracle简单存储过程以及如何查看编译错误

    oracle简单存储过程以及如何查看编译错误; CREATE OR REPLACE PROCEDURE procedure_test ISval VARCHAR2(200);BEGIN /* val ...

  8. Yii---使用事物

    YII使用事物的时候,遇到的一些小问题总结:开始事物,后要进行事物提交,才能操作数据库(折腾了一天)具体使用: yii事物的定义:是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不 ...

  9. C++虚函数virtual,纯虚函数pure virtual和Java抽象函数abstract,接口interface与抽象类abstract class的比较

    由于C++和Java都是面向对象的编程语言,它们的多态性就分别靠虚函数和抽象函数来实现. C++的虚函数可以在子类中重写,调用是根据实际的对象来判别的,而不是通过指针类型(普通函数的调用是根据当前指针 ...

  10. 被included或者被required的文件都来自哪里呢

    过PHP,你可以使用不同函数帮助你重用代码.具体用到的函数取决于你打算重用的内容. 主函数如下: * include() and include_once() * require() and requ ...