LeetCode: 785. 判断二分图¶
1、题目描述¶
给定一个无向图graph
,当这个图为二分图时返回true
。
如果我们能将一个图的节点集合分割成两个独立的子集A
和B
,并使图中的每一条边的两个节点一个来自A
集合,一个来自B
集合,我们就将这个图称为二分图。
graph
将会以邻接表方式给出,graph[i]
表示图中与节点i相连的所有节点。每个节点都是一个在0
到graph.length-1
之间的整数。这图中没有自环和平行边: graph[i]
中不存在i
,并且graph[i]
中没有重复的值。
示例 1:
输入: [[1,3], [0,2], [1,3], [0,2]] 输出: true 解释: 无向图如下: 0----1 | | | | 3----2 我们可以将节点分成两组: {0, 2} 和 {1, 3}。
示例 2:
输入: [[1,2,3], [0,2], [0,1,3], [0,2]] 输出: false 解释: 无向图如下: 0----1 | \ | | \ | 3----2 我们不能将节点分割成两个独立的子集。
注意:
注意:
graph 的长度范围为 [1, 100]。
graph[i] 中的元素的范围为 [0, graph.length - 1]。
graph[i] 不会包含 i 或者有重复的值。
图是无向的: 如果j 在 graph[i]里边, 那么 i 也会在 graph[j]里边。
2、解题思路¶
- 广度优先搜索
如果想要满足题目中的条件,那么对图进行广度优先搜索,如果下级节点的子集同时在下级节点的集合中,就表示有相连两个点在同一个集合中,不满足条件
- 需要考虑森林的情况,有些节点是孤立的
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: if not graph: return True length = len(graph) visited = [False] * length def judge(nodes: List[int]): while nodes: temp = set() for n in nodes: visited[n] = True for node in nodes: for nex in graph[node]: if not visited[nex]: if set(graph[nex]) & temp: return False temp.add(nex) nodes = list(temp) return True while not all(visited): for index, v in enumerate(visited): if not v: d = [index] if not judge(d): return False return True