using System; using System.Collections.Generic; class Graph { private int V; private List<int>[] adj; public Graph(int v) { V = v; adj = new List<int>[v]; for (int i = 0; i < v; i++) { adj[i] = new List<int>(); } } public void AddEdge(int v, int w) { adj[v].Add(w); adj[w].Add(v); } public void BFS(int s) { bool[] visited = new bool[V]; Queue<int> queue = new Queue<int>(); visited[s] = true; queue.Enqueue(s); while (queue.Count != 0) { s = queue.Dequeue(); Console.Write(s + " "); foreach (int n in adj[s]) { if (!visited[n]) { visited[n] = true; queue.Enqueue(n); } } } } } class Program { static void Main() { Graph g = new Graph(4); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 3); g.BFS(0); } }
BFS starts at node 0, visits its neighbors 1 and 2 in order, then visits neighbors of 1 and 2. Node 3 is neighbor of 2, so it is visited last.
BFS uses a queue to process nodes in the order they are discovered, which ensures nodes are visited level by level from the source.
bool[] visited = new bool[V]; Queue<int> queue = new Queue<int>(); visited[s] = true; queue.Enqueue(s); while (queue.Count != 0) { s = queue.Dequeue(); Console.Write(s + " "); foreach (int n in adj[s]) { if (visited[n]) { visited[n] = true; queue.Enqueue(n); } } }
The condition 'if (visited[n])' is incorrect. It should be 'if (!visited[n])' to enqueue unvisited neighbors. Because of this, no new nodes are enqueued after the start node.
BFS can find shortest paths by tracking distance from source when nodes are first visited. Using a queue ensures shortest paths are found first.
using System; using System.Collections.Generic; class Graph { private int V; private List<int>[] adj; public Graph(int v) { V = v; adj = new List<int>[v]; for (int i = 0; i < v; i++) { adj[i] = new List<int>(); } } public void AddEdge(int v, int w) { adj[v].Add(w); adj[w].Add(v); } public void BFS(int s) { bool[] visited = new bool[V]; Queue<int> queue = new Queue<int>(); visited[s] = true; queue.Enqueue(s); while (queue.Count != 0) { s = queue.Dequeue(); Console.Write(s + " "); foreach (int n in adj[s]) { if (!visited[n]) { visited[n] = true; queue.Enqueue(n); } } } } } class Program { static void Main() { Graph g = new Graph(6); g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(3, 4); g.AddEdge(4, 5); g.BFS(0); } }
The graph has two disconnected parts: nodes 0,1,2 and nodes 3,4,5. Starting BFS at 0 visits only nodes 0,1,2.
