Shortest Path in a Binary Weight Graph (original) (raw)
`using System; using System.Collections.Generic;
class Program { static int MAX_VALUE = int.MaxValue;
static List<int> minDist(int n, int src, List<Tuple<int, int>>[] adj){
// Initialize distances to infinity
int[] dist = new int[n];
Array.Fill(dist, MAX_VALUE);
dist[src] = 0;
// Use Queue for 0-1 BFS
Queue<int> dq = new Queue<int>();
dq.Enqueue(src);
while (dq.Count > 0){
int u = dq.Dequeue();
// 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.Enqueue(v);
}
else{
dq.Enqueue(v);
}
}
}
}
return new List<int>(dist);
}
static void Main()
{
int n = 9;
int src = 0;
var edges = new List<Tuple<int, int, int>>
{
new Tuple<int, int, int>(0, 1, 0),
new Tuple<int, int, int>(0, 7, 1),
new Tuple<int, int, int>(1, 2, 1),
new Tuple<int, int, int>(1, 7, 1),
new Tuple<int, int, int>(2, 3, 0),
new Tuple<int, int, int>(2, 5, 0),
new Tuple<int, int, int>(2, 8, 1),
new Tuple<int, int, int>(3, 4, 1),
new Tuple<int, int, int>(3, 5, 1),
new Tuple<int, int, int>(4, 5, 1),
new Tuple<int, int, int>(5, 6, 1),
new Tuple<int, int, int>(6, 7, 1),
new Tuple<int, int, int>(7, 8, 1)
};
// Create adjacency list representation of the graph
var 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)
{
adj[edge.Item1].Add(new Tuple<int, int>(edge.Item2, edge.Item3));
adj[edge.Item2].Add(new Tuple<int, int>(edge.Item1, edge.Item3));
}
var res = minDist(n, src, adj);
foreach (var d in res)
{
Console.Write(d + " ");
}
Console.WriteLine();
}}
`