// C# program to implement 0-1 BFS // (Shortest Path in a Binary Weight Graph) using System; using System.Collections.Generic; class GfG { static int[] MinDist(int n, int src, int[][] edges) { // Create adjacency list representation of the graph List<Tuple<int, int>>[] adj = new List<Tuple<int, int>>[n]; for (int i = 0; i < n; i++) { adj[i] = new List<Tuple<int, int>>(); } foreach (var edge in edges) { int u = edge[0]; int v = edge[1]; int w = edge[2]; adj[u].Add(Tuple.Create(v, w)); adj[v].Add(Tuple.Create(u, w)); } // Initialize distances to infinity int[] dist = new int[n]; for (int i = 0; i < n; i++) { dist[i] = int.MaxValue; } dist[src] = 0; // Use deque for 0-1 BFS LinkedList<int> dq = new LinkedList<int>(); dq.AddLast(src); while (dq.Count > 0) { int u = dq.First.Value; dq.RemoveFirst(); // Process all adjacent vertices foreach (var edge in adj[u]) { int v = edge.Item1; int weight = edge.Item2; // If we can improve the distance if (dist[u] + weight < dist[v]) { dist[v] = dist[u] + weight; // If weight is 0, push to front (higher priority) // If weight is 1, push to back (lower priority) if (weight == 0) dq.AddFirst(v); else dq.AddLast(v); } } } return dist; } static void Main() { int n = 9, src = 0; int[][] edges = new int[][] { new int[] {0, 1, 0}, new int[] {0, 7, 1}, new int[] {1, 2, 1}, new int[] {1, 7, 1}, new int[] {2, 3, 0}, new int[] {2, 5, 0}, new int[] {2, 8, 1}, new int[] {3, 4, 1}, new int[] {3, 5, 1}, new int[] {4, 5, 1}, new int[] {5, 6, 1}, new int[] {6, 7, 1}, new int[] {7, 8, 1} }; int[] res = MinDist(n, src, edges); foreach (int val in res) { Console.Write(val + " "); } Console.WriteLine(); } }