题目描述
Given a
graph, returntrueif 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 indexesjfor which the edge between nodesiandjexists. Each node is an integer between0andgraph.length - 1. There are no self edges or parallel edges:graph[i]does not containi, and it doesn’t contain any element twice.
即判断给定的图是否是二分图:
设G=(V,E)是一个无向图,如果顶点V可分割为两个互不相交的子集(A,B),并且图中的每条边(i,j)所关联的两个顶点i和j分别属于这两个不同的顶点集(i in A, j in B),则称图G为一个二分图。
算法分析
二分图的判断可以看作染色问题。对于图中的每一个顶点S,与它直接相邻的任一顶点N,其颜色必然与S不同,则这样的图是一个二分图。
最常用也最简单的方法就是遍历(DFS或BFS)整张图,用两种不同的颜色A和B,对每个顶点染色。选定一个顶点S开始,对其进行染色,再访问它的邻居顶点N。若:
N还未被染色,即对它染色与S不同的颜色,并继续访问S的邻居顶点。N已被染色,且其颜色与S相同,则该图不是一个二分图。N已被染色,但其颜色与S不同,则继续查看和访问其它邻居节点。