using System; using System.Collections.Generic; class Program { static void Main() { int n = 5; List<int>[] graph = new List<int>[n]; for (int i = 0; i < n; i++) graph[i] = new List<int>(); graph[0].Add(1); graph[0].Add(2); graph[1].Add(2); graph[1].Add(3); graph[2].Add(3); graph[3].Add(4); int[] dist = new int[n]; for (int i = 0; i < n; i++) dist[i] = -1; dist[0] = 0; Queue<int> q = new Queue<int>(); q.Enqueue(0); while (q.Count > 0) { int u = q.Dequeue(); foreach (int v in graph[u]) { if (dist[v] == -1) { dist[v] = dist[u] + 1; q.Enqueue(v); } } } Console.WriteLine(string.Join(",", dist)); } }
The BFS starts from node 0 with distance 0. It visits nodes 1 and 2 next, assigning distance 1. Then node 3 is reached from nodes 1 or 2 with distance 2, and finally node 4 from node 3 with distance 3.
BFS explores nodes in layers, starting from the source node and moving outward. This ensures the first time a node is visited, it is via the shortest path.
int n = 4; List<int>[] graph = new List<int>[n]; for (int i = 0; i < n; i++) graph[i] = new List<int>(); graph[0].Add(1); graph[1].Add(2); graph[2].Add(3); int[] dist = new int[n]; for (int i = 0; i < n; i++) dist[i] = -1; dist[0] = 0; Queue<int> q = new Queue<int>(); q.Enqueue(0); while (q.Count > 0) { int u = q.Dequeue(); foreach (int v in graph[u]) { if (dist[v] == 0) { dist[v] = dist[u] + 1; q.Enqueue(v); } } } Console.WriteLine(string.Join(",", dist));
The condition 'if (dist[v] == 0)' is wrong because distance 0 means the node is the start node. Unvisited nodes have distance -1. This causes nodes to be revisited incorrectly, leading to infinite loops or wrong distances.
using System; using System.Collections.Generic; class Program { static void Main() { int n = 5; List<int>[] graph = new List<int>[n]; for (int i = 0; i < n; i++) graph[i] = new List<int>(); graph[0].Add(1); graph[0].Add(2); graph[1].Add(3); graph[2].Add(3); graph[3].Add(4); int[] dist = new int[n]; int[] parent = new int[n]; for (int i = 0; i < n; i++) { dist[i] = -1; parent[i] = -1; } dist[0] = 0; Queue<int> q = new Queue<int>(); q.Enqueue(0); while (q.Count > 0) { int u = q.Dequeue(); foreach (int v in graph[u]) { if (dist[v] == -1) { dist[v] = dist[u] + 1; parent[v] = u; q.Enqueue(v); } } } List<int> path = new List<int>(); int cur = 4; while (cur != -1) { path.Add(cur); cur = parent[cur]; } path.Reverse(); Console.WriteLine(string.Join(" -> ", path) + " -> null"); } }
Node 3 is first reached from node 1, so parent[3] = 1. The path from 0 to 4 is 0 -> 1 -> 3 -> 4.
BFS visits each vertex once and explores all edges from each vertex once, resulting in O(V + E) time complexity.
