AlgoMaster Logo

Is Graph Bipartite?

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Depth First Search (DFS) with Two Colors

Intuition:

A graph is bipartite if its nodes can be divided into two independent sets such that no two graph nodes within the same set are adjacent. We can utilize a two-color technique, where we attempt to color the graph using two colors and verify that no two adjacent nodes have the same color. This can be efficiently done using Depth First Search (DFS).

Steps:

  1. Initialize a color array to keep track of the color assigned to each node (e.g., use -1, 0, and 1, where -1 indicates uncolored).
  2. Traverse each node in the graph. If a node is uncolored, apply DFS to color it and its connected components.
  3. During DFS, ensure no two adjacent nodes have the same color. If two adjacent nodes share a color, the graph is not bipartite.
  4. If all nodes can be properly colored, then the graph is bipartite.

Code:

2. Breadth First Search (BFS) with Two Colors

Intuition:

Another way to solve the problem using two-coloring is to utilize Breadth First Search (BFS). This approach uses a queue to explore each level of the graph and ensures that adjacent nodes are assigned different colors.

Steps:

  1. Create a color array similar to the DFS approach.
  2. Use a queue to perform BFS on each uncolored component of the graph.
  3. Attempt to color each node and its neighbors with alternating colors.
  4. If any adjacent nodes have the same color during BFS traversal, the graph is not bipartite.

Code: