Is Graph Bipartite?
Problem statement
You are given an adjacency-list representation of an undirected graph. The vertices are numbered from 0 through graph.length - 1, and graph[u] lists every neighbor of vertex u.
Return true when the vertices can be divided into two groups such that every edge connects vertices from different groups. Otherwise, return false.
The graph may be disconnected.
Function
isBipartite(graph: int[][]) → booleanExamples
Example 1
graph = [[1,2,3],[0,2],[0,1,3],[0,2]]return = falseVertices 0, 1, and 2 form an odd cycle.
Example 2
graph = [[1,3],[0,2],[1,3],[0,2]]return = trueOne valid partition is {0, 2} and {1, 3}.
Example 3
graph = [[],[]]return = trueTwo isolated vertices have no conflicting edge.
Constraints
1 <= graph.length <= 500- Every neighbor is in the range from
0throughgraph.length - 1. - No vertex lists itself, and a neighbor appears at most once in one adjacency list.
- The graph is undirected: if
vappears ingraph[u], thenuappears ingraph[v].