forked from mburst/dijkstras-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstras.cs
93 lines (78 loc) · 2.87 KB
/
dijkstras.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections.Generic;
namespace Dijkstras
{
class Graph
{
Dictionary<char, Dictionary<char, int>> vertices = new Dictionary<char, Dictionary<char, int>>();
public void add_vertex(char name, Dictionary<char, int> edges)
{
vertices[name] = edges;
}
public List<char> shortest_path(char start, char finish)
{
var previous = new Dictionary<char, char>();
var distances = new Dictionary<char, int>();
var nodes = new List<char>();
List<char> path = null;
foreach (var vertex in vertices)
{
if (vertex.Key == start)
{
distances[vertex.Key] = 0;
}
else
{
distances[vertex.Key] = int.MaxValue;
}
nodes.Add(vertex.Key);
}
while (nodes.Count != 0)
{
nodes.Sort((x, y) => distances[x] - distances[y]);
var smallest = nodes[0];
nodes.Remove(smallest);
if (smallest == finish)
{
path = new List<char>();
while (previous.ContainsKey(smallest))
{
path.Add(smallest);
smallest = previous[smallest];
}
break;
}
if (distances[smallest] == int.MaxValue)
{
break;
}
foreach (var neighbor in vertices[smallest])
{
var alt = distances[smallest] + neighbor.Value;
if (alt < distances[neighbor.Key])
{
distances[neighbor.Key] = alt;
previous[neighbor.Key] = smallest;
}
}
}
return path;
}
}
class MainClass
{
public static void Main(string[] args)
{
Graph g = new Graph();
g.add_vertex('A', new Dictionary<char, int>() {{'B', 7}, {'C', 8}});
g.add_vertex('B', new Dictionary<char, int>() {{'A', 7}, {'F', 2}});
g.add_vertex('C', new Dictionary<char, int>() {{'A', 8}, {'F', 6}, {'G', 4}});
g.add_vertex('D', new Dictionary<char, int>() {{'F', 8}});
g.add_vertex('E', new Dictionary<char, int>() {{'H', 1}});
g.add_vertex('F', new Dictionary<char, int>() {{'B', 2}, {'C', 6}, {'D', 8}, {'G', 9}, {'H', 3}});
g.add_vertex('G', new Dictionary<char, int>() {{'C', 4}, {'F', 9}});
g.add_vertex('H', new Dictionary<char, int>() {{'E', 1}, {'F', 3}});
g.shortest_path('A', 'H').ForEach( x => Console.WriteLine(x) );
}
}
}