Problem · Graph
Check Bipartite Graph
Learn this problemProblem statement
You are given a square binary matrix edges describing an undirected graph with vertices numbered from 0 through n - 1.
Vertices i and j are connected when edges[i][j] == 1 or edges[j][i] == 1. This convention allows an edge to be recorded in either half of the matrix.
Return true if the vertices can be divided into two groups such that every edge joins vertices from different groups. Otherwise, return false.
Function
isGraphBipartite(edges: int[][]) → booleanExamples
Example 1
edges = [[0,1,0,0],[0,0,0,1],[0,0,0,0],[0,0,0,0]]return = trueThe only edges are 0-1 and 1-3. One valid partition is {0, 3} and {1, 2}.
Example 2
edges = [[0,1,1],[0,0,1],[0,0,0]]return = falseVertices 0, 1, and 2 form an odd cycle, so two groups are impossible.
Example 3
edges = [[0,1,0,1,0],[1,0,1,0,0],[0,1,0,1,0],[1,0,1,0,0],[0,0,0,0,0]]return = trueThe four connected vertices form an even cycle, and vertex 4 is isolated. Every component is bipartite.
Constraints
2 <= edges.length <= 300edges[i].length == edges.lengthedges[i][j]is either0or1.edges[i][i] == 0- An undirected edge is present when either
edges[i][j]oredges[j][i]is1.