2018年9月23日
#785 Is Graph Bipartite?
问题描述:
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]
.
问题分析:
本题难度为Medium!已给出的函数定义为:
class Solution:
def isBipartite(self, graph):
"""
:type graph: List[List[int]]
:rtype: bool
"""
其中graph为一个二维数组,返回值为布尔类型值;
本题是判断一个无向图是否为二分图,判断二分图方法有很多,这里采用算法实现上比较简单的染色法。
算法如下:
用colornodes列表记录结点的染色情况(-1/1),用visited列表记录结点的访问情况(0/1)
通过广度优先搜索bfs遍历每一个结点:
建立bfslist列表;
while 有结点未被访问:
若bfslist为空,则选则一个未访问的结点,染色,标记该结点已访问,并添加到bfslist后;
若bfslist不为空,则遍历该结点的子结点:
若该子结点未被访问,则染色(与父结点颜色不同),标记为已访问,并添加到bsflist后;
遍历graph表,若存在相邻结点颜色相同,则不是二分图,否则,是二分图;
代码实现:
#coding=utf-8
class Solution:
def isBipartite(self, graph):
"""
:type graph: List[List[int]]
:rtype: bool
"""
visited=[0 for i in range(len(graph))] #访问过的结点标记为1
colornodes=[0 for i in range(len(graph))] #store the color of each node,-1/1
curnode=0 #当前结点
color=-1 #初始颜色为-1
bfslist=[] #bfs队列
while sum(visited)!=len(graph):
if len(bfslist)==0: #bfs队列为空
i=visited.index(0) #未访问过的结点
visited[i]=1 #标记已访问
colornodes[i]=color #染色
bfslist.append(i) #加到bfs队列中
else:
curnode=bfslist.pop(0) #pop第一个元素
color = colornodes[curnode]*-1# 切换染色颜色
for i in graph[curnode]:
if visited[i]==0: #处理未访问过的结点
visited[i]=1 #标记已访问
colornodes[i]=color #染色
bfslist.append(i) #加到bfs队列中
for i in range(len(graph)):
for j in range(len(graph[i])):
if colornodes[i]==colornodes[graph[i][j]]:
return False
return True