 All Problems
Is Graph Bipartite?
medium
graph
breadth-first search
depth-first search
union find
facebook
google
amazon

There is an undirected graph with n nodes. The graph is represented as a 0-indexed 2D integer array graph where graph[u] is an array of nodes that node u is adjacent to.

Return true if and only if the graph is bipartite. A graph is bipartite if we can split its nodes into two independent sets A and B such that every edge connects a node in A to one in B.

Example 1:

Input:
4
1 3
0 2
1 3
0 2
Output: true

Example 2:

Input:
4
1 2 3
0 2
0 1 3
0 2
Output: false

Constraints:

  • graph.length == n
  • 1 ≤ n ≤ 100
  • 0 ≤ graph[u].length < n
  • 0 ≤ graph[u][i] ≤ n-1
  • No self-loops, no repeated edges

Input format: First line: n. Then n lines, each with space-separated neighbors (empty line for isolated node).

Output format: true or false.

Run to check your code against the sample cases, or submit to run every case