博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 785 Is Graph Bipartite? 图着色
阅读量:4186 次
发布时间:2019-05-26

本文共 2072 字,大约阅读时间需要 6 分钟。

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: trueExplanation: The graph looks like this:0----1|    ||    |3----2We 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: falseExplanation: The graph looks like this:0----1| \  ||  \ |3----2We 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].

Accepted

79,350

Submissions

173,231

--------------------------------------------------------------------------------------------

图着色,DFS或者BFS着色,碰到不行的就是False。实际中,DFS用个栈就可以写非递归,写起来简单很多,如下:

class Solution:    def isBipartite(self, graph):        colors = {}        for i in range(len(graph)):            if (i not in colors):                colors[i] = 0                sta = [i]                while (sta):                    node = sta.pop()                    for nxt in graph[node]:                        if (nxt in colors and colors[nxt] == colors[node]):                            return False                        elif (nxt not in colors): #bug2                            colors[nxt] = colors[node] ^ 1 #bug1                            sta.append(nxt)        return Trues = Solution()print(s.isBipartite([[1,3], [0,2], [1,3], [0,2]]))print(s.isBipartite([[1,2,3], [0,2], [0,1,3], [0,2]]))

 

转载地址:http://dtfoi.baihongyu.com/

你可能感兴趣的文章
链表类型题目需要用到的头文件list.h
查看>>
tree类型题目需要用到的头文件tree.h
查看>>
有一个1亿结点的树,已知两个结点, 求它们的最低公共祖先!
查看>>
BST(binary search tree)类型题目需要用到的头文件binary_tree.h
查看>>
将BST转换为有序的双向链表!
查看>>
中体骏彩C++面试题
查看>>
永成科技C++笔试题
查看>>
webkit入门准备
查看>>
在Ubuntu 12.04 64bit上配置,安装和运行go程序
查看>>
ATS程序功能和使用方法详解
查看>>
常用Linux命令总结
查看>>
Tafficserver旁路接入方案综述
查看>>
在CentOS 6.3 64bit上如何从源码生成rpm包?
查看>>
利用lua中的string.gsub来巧妙实现json中字段的正则替换
查看>>
ATS名词术语(待续)
查看>>
ATS缓存相关话题
查看>>
ATS中的RAM缓存简介
查看>>
CDN和Web Cache领域相关的经典书籍推荐
查看>>
在Oracle VM VirtualBox中如何安装64位虚拟机系统
查看>>
安装和使用Oracle VM VirtualBox中的要点,注意事项和遇到的问题
查看>>