Is the graph bipartite?
Standard · Write code · about 12 min
Return true if the nodes of the undirected graph can be split into two groups so that every edge joins a node of one group to a node of the other. Otherwise return false. In JavaScript, buildAdjacency(graph) returns the adjacency lists.
Example 1
Input:
[{"n":4,"edges":[[0,1],[1,2],[2,3],[3,0]],"directed":false}]
Output:
true
Groups {0, 2} and {1, 3}.
Example 2
Input:
[{"n":4,"edges":[[0,1],[1,2],[2,0],[2,3]],"directed":false}]
Output:
false
Nodes 0, 1 and 2 form an odd cycle.
Constraints
- 1 ≤ n ≤ 200 nodes, numbered 0 to n - 1
- At most 3n edges; repeated edges and self-loops may appear
- The graph is undirected and may be disconnected
Learn the idea first: Bipartite check by 2-coloring, a visual lesson.
More Bipartite check by 2-coloring problems
- Possible bipartition Standard
- Return the 2-coloring Standard
- Odd cycle witness Standard