⬅ Previous Topic
Number of Distinct Islands using DFSNext Topic ⮕
Topological Sort Using DFS⬅ Previous Topic
Number of Distinct Islands using DFSNext Topic ⮕
Topological Sort Using DFSTopic Contents
Given an undirected graph represented as an adjacency list with V
vertices (0-indexed), determine if the graph is bipartite.
A graph is bipartite if we can split the set of vertices into two groups such that no two adjacent vertices belong to the same group. This is equivalent to checking if the graph can be coloured using two colours without any two adjacent nodes having the same colour.
color
array of size V
initialized with -1
(unvisited).dfs
function that takes current node
and currentColor
.dfs
with opposite colour.function isBipartiteDFS(adj, V) {
const color = new Array(V).fill(-1);
function dfs(node, c) {
color[node] = c;
for (const neighbor of adj[node] || []) {
if (color[neighbor] === -1) {
if (!dfs(neighbor, 1 - c)) return false;
} else if (color[neighbor] === color[node]) {
return false;
}
}
return true;
}
for (let i = 0; i < V; i++) {
if (color[i] === -1) {
if (!dfs(i, 0)) return false;
}
}
return true;
}
// Example usage
const graph1 = { 0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2] };
console.log("Is graph1 bipartite?", isBipartiteDFS(graph1, 4)); // true
const graph2 = { 0: [1, 2], 1: [0, 2], 2: [0, 1] };
console.log("Is graph2 bipartite?", isBipartiteDFS(graph2, 3)); // false
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | Even in the best case, we must traverse all vertices and their edges to ensure bipartite coloring without assumptions. |
Average Case | O(V + E) | Each vertex and edge is visited once during the DFS traversal. |
Worst Case | O(V + E) | In the worst case, the graph is fully connected and requires full traversal of all vertices and edges. |
O(V)
Explanation: We use a color array of size V and recursive call stack of maximum depth V in the worst case.
⬅ Previous Topic
Number of Distinct Islands using DFSNext Topic ⮕
Topological Sort Using DFSYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.