find shortest path between 25 nodes in csharp

To find the shortest path between 25 nodes, you can use Dijkstra's algorithm in C#. Dijkstra's algorithm is a popular algorithm for finding the shortest path between nodes in a graph.

Here is an implementation of Dijkstra's algorithm in C#:

main.cs
using System;
using System.Collections.Generic;

public class GraphNode {
    public int Id;
    public List<Edge> Edges = new List<Edge>();
    
    public GraphNode(int id) {
        Id = id;
    }
}

public class Edge {
    public int Weight;
    public GraphNode Target;
    
    public Edge(GraphNode target, int weight) {
        Weight = weight;
        Target = target;
    }
}

public static void DijkstraShortestPath(List<GraphNode> graph, GraphNode start, GraphNode end) {
    Dictionary<GraphNode, int> distances = new Dictionary<GraphNode, int>();
    Dictionary<GraphNode, GraphNode> previousNodes = new Dictionary<GraphNode, GraphNode>();
    List<GraphNode> unvisitedNodes = new List<GraphNode>();
  
    // Initialize all distances to Infinity except the start node
    foreach (var node in graph) {
        if (node == start) {
            distances[node] = 0;
        } else {
          distances[node] = int.MaxValue;
        }
        unvisitedNodes.Add(node);
    }
    
    // Calculate shortest paths
    while (unvisitedNodes.Count > 0) {
        // Sort nodes by distance, choose the closest node
        unvisitedNodes.Sort((x, y) => distances[x] - distances[y]);
        GraphNode current = unvisitedNodes[0];
        unvisitedNodes.Remove(current);
        
        // Stop if distance to the current node is Infinity
        if (distances[current] == int.MaxValue) {
            break;
        }
        
        // Update distances and previous nodes of current node's neighbors
        foreach (Edge e in current.Edges) {
            int alt = distances[current] + e.Weight;
            if (alt < distances[e.Target]) {
                distances[e.Target] = alt;
                previousNodes[e.Target] = current;
            }
        }
    }
    
    // Build the path from end to start
    Stack<GraphNode> path = new Stack<GraphNode>();
    GraphNode node = end;
    while (node != start) {
        path.Push(node);
        node = previousNodes[node];
    }
    path.Push(start);
        
    // Print the shortest path and distance
    Console.Write("Shortest path: ");
    while (path.Count > 0) {
        Console.Write(path.Pop().Id);
        if (path.Count > 0) {
            Console.Write(" -> ");
        }
    }
    Console.WriteLine("\nDistance: " + distances[end]);
}

2314 chars
80 lines

To use this code, you need to create a list of GraphNodes and populate their edges. Each GraphNode should have an Id and a list of Edges. Each Edge should have a Target and a Weight. Then call DijkstraShortestPath with the graph, start node, and end node.

gistlibby LogSnag