You are given an n x n graph represented by an adjacency matrix, where graph[u] is a list of nodes v such that there is an edge between node u and node v. Return true if the graph is bipartite. A graph is bipartite if we can split its set of nodes into two independent subsets A and B such that every edge in the graph connects a node in set A and a node in set B.
To determine if a graph is bipartite, we can use a two-coloring technique. We will try to color the graph using two colors such that no two adjacent nodes share the same color. This can be done using either Depth-First Search (DFS) or Breadth-First Search (BFS).
Here’s the implementation using BFS:
from collections import deque
def isBipartite(graph):
n = len(graph)
color = [-1] * n # Color array to store colors of nodes, -1 means uncolored
for start in range(n):
if color[start] == -1: # Uncolored node, start a BFS/DFS from here
queue = deque([start])
color[start] = 0 # Start coloring with 0
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if color[neighbor] == -1:
# Color with the opposite color
color[neighbor] = 1 - color[node]
queue.append(neighbor)
elif color[neighbor] == color[node]:
# If neighbor has the same color, graph is not bipartite
return False
return True
O(V + E), where V is the number of vertices and E is the number of edges. Each node and each edge is processed at most once.O(V), for storing the color array and the queue.This ensures we handle both connected and disconnected components by initiating a BFS search from every uncolored node.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?