Is Graph Bipartite?
Check whether an undirected graph can be partitioned into two independent sets using 2-coloring BFS.
01The problem
There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to.
A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.
Return true if and only if it is bipartite.
| Input | Output | Why |
|---|---|---|
graph = [[1,2,3],[0,2],[0,1,3],[0,2]] | false | Triangle 0-1-2 forms an odd cycle, impossible to 2-color. |
graph = [[1,3],[0,2],[1,3],[0,2]] | true | Even square cycle 0-1-2-3 can be 2-colored: {0, 2} and {1, 3}. |
Constraints
graph.length == n1 <= n <= 1000 <= graph[u].length < n0 <= graph[u][i] <= n - 1graph[u]does not containu(no self-loops).- All values in
graph[u]are unique. - The graph may be disconnected.
Loading the rest of the lesson…