-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra.cs
95 lines (90 loc) · 2.58 KB
/
Dijkstra.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
94
95
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms
{
internal class Dijkstra
{
internal class NodeRef
{
public Node Node { get; set; }
public int Cost { get; set; }
};
internal class Node
{
public string Name { get; set; }
public int MinCost { get; set; }
public Node Parent { get; set; }
public List<NodeRef> Nodes { get; set; }
}
internal static void Run()
{
// 5 - C - 4
// A 1 D
// 3 - B - 7
var d = new Node()
{
Name = "D",
MinCost = int.MaxValue,
Parent = null,
Nodes = new List<NodeRef>
{
}
};
var c = new Node()
{
Name = "C",
MinCost = int.MaxValue,
Parent = null,
Nodes = new List<NodeRef>
{
new NodeRef() { Node = d, Cost = 4 }
}
};
var b = new Node()
{
Name = "B",
MinCost = int.MaxValue,
Parent = null,
Nodes = new List<NodeRef>
{
new NodeRef() { Node = c, Cost = 1 },
new NodeRef() { Node = d, Cost = 7 }
}
};
var a = new Node()
{
Name = "A",
MinCost = 0,
Parent = null,
Nodes = new List<NodeRef>
{
new NodeRef() { Node = b, Cost = 3 },
new NodeRef() { Node = c, Cost = 5 }
}
};
int mincost = FindMinCost(a, d);
}
private static int FindMinCost(Node start, Node target)
{
Stack<Node> stack = new Stack<Node>();
stack.Push(start);
Node node;
while (stack.TryPop(out node))
{
foreach (var n in node.Nodes) // go through all paths of node
{
if (n.Cost + node.MinCost < n.Node.MinCost)
{
n.Node.MinCost = n.Cost + node.MinCost;
n.Node.Parent = node;
}
stack.Push(n.Node);
}
}
return target.MinCost;
}
}
}