Tutorialspoint
Problem
Solution
Submissions

Graph is Bipartite

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to implement the isBipartite(int[][] graph) function, which determines if a given undirected graph can be colored with exactly two colors such that no two adjacent vertices share the same color. The graph is given as an adjacency list where graph[i] contains all the neighbors of vertex i.

Example 1
  • Input: graph = [[1,3],[0,2],[1,3],[0,2]]
  • Output: true
  • Explanation:
    • We can color vertex 0 with color 0, vertex 1 with color 1, vertex 2 with color 0, and vertex 3 with color 1.
    • No two adjacent vertices share the same color.
Example 2
  • Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
  • Output: false
  • Explanation:
    • There is no way to color the vertices with two colors without adjacent vertices sharing the same color.
    • For example, if vertex 0 has color 0, then vertices 1, 2, and 3 must all have color 1.
    • But vertices 1 and 2 are adjacent, so they cannot have the same color.
Constraints
  • 1 ≤ graph.length ≤ 100
  • 0 ≤ graph[i].length ≤ 100
  • graph[i] does not contain i
  • There are no self-loops or parallel edges
  • Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges
  • Space Complexity: O(V)
GraphTech MahindraTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use either Breadth-First Search (BFS) or Depth-First Search (DFS) to traverse the graph
  • Assign colors (e.g., 0 and 1) to vertices as you visit them
  • If you encounter a vertex that has already been colored and its color conflicts with what it should be, the graph is not bipartite
  • Remember to handle disconnected components of the graph
  • Use an array to track the color of each vertex

Steps to solve by this approach:

 Step 1: Create an array to store the color of each vertex (-1 for uncolored, 0 and 1 for the two colors).
 Step 2: For each uncolored vertex, start a BFS traversal.
 Step 3: Color the starting vertex and enqueue it.
 Step 4: For each vertex in the queue, calculate the expected color of its neighbors (opposite of the current vertex's color).
 Step 5: For each neighbor, if it's uncolored, color it with the expected color and enqueue it.
 Step 6: If a neighbor is already colored and its color doesn't match the expected color, the graph is not bipartite.
 Step 7: If all vertices can be colored without conflicts, the graph is bipartite.

Submitted Code :