-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdijkstra.rb
More file actions
148 lines (108 loc) · 3.21 KB
/
dijkstra.rb
File metadata and controls
148 lines (108 loc) · 3.21 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class Dijkstra
def initialize(filename, startpoint, endpoint)
#start node
@start = startpoint
#end node
@end = endpoint
#in this vector we will hold the shortest path
@path = []
#PInfinit
@PInfinit = 88
#read and init the father array, selected array and road array
readAndInit(filename)
#Dijkstra's algorithm in action and good luck
dijkstra()
end
# This method determines the minimum cost of the shortest path
def getCost()
@R[@end]
end
# get the shortest path
def getShortestPath()
ROAD(@end)
@path
end
def ROAD(node)
if @F[node] != 0
ROAD(@F[node])
end
@path.push(node)
end
def dijkstra()
start = @start
min = @PInfinit
posMin = @PInfinit
(1..@nodes-1).each do |i|
@R[i] = @road[start][i]
if i != start
if @R[i] < @PInfinit
@F[i] = start
end
end
end
#for debug
#print @R
@S[start] = 1
#for debug
#print @S
(1..@nodes-2).each do |d|
min = @PInfinit
(1..@nodes-1).each do |i|
if @S[i] == 0
if @R[i] < min
min = @R[i]
posMin = i
end
end
end
@S[posMin] = 1
(1..@nodes-1).each do|j|
if @S[j] == 0
if @R[j] > @R[posMin] + @road[posMin][j]
@R[j] = @R[posMin] + @road[posMin][j]
@F[j] = posMin
end
end
end
end
end
def readAndInit(file)
arr = []
File.open(file, "r").each_line { |line| arr << line.split(' ').map {|c| c.to_i} }
@nodes = arr[0][0] + 1
n = arr.size()-1
@road = Array.new(@nodes) { Array.new(@nodes) }
@R = Array.new(@nodes)
@S = Array.new(@nodes)
@F = Array.new(@nodes)
(0..@nodes-1).each do |i|
@R[i] = 0
end
(0..@nodes-1).each do |i|
@S[i] = 0
end
(0..@nodes-1).each do |i|
@F[i] = 0
end
(0..@nodes-1).each do |i|
(0..@nodes-1).each do |j|
if i == j
@road[i][j] = 0
else
@road[i][j] = @PInfinit
end
end
end
(1..n).each do |i|
x = arr[i][0]
y = arr[i][1]
c = arr[i][2]
@road[x][y] = c
end
end
end
start_point = 1
end_point = 3
ob = Dijkstra.new('dijkstra.in', start_point, end_point)
print "Cost = ", ob.getCost(), "\n"
print "Shortest Path = ", ob.getShortestPath()