aboutsummaryrefslogtreecommitdiff
path: root/challenge-121/abigail/ruby/ch-2.rb
blob: 9696710e358c25cb63efd52b0104042e58d0f493 (plain)
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
#!/usr/bin/ruby

#
# See ../README.md
#
 
#
# Run as: ruby ch-2.rb < input-file
#

matrix = []

def shortest_path (matrix, from, to, exclude)
    if 1 + exclude . size() == matrix . length() then
        return matrix [from] [to], [to]
    end

    shortest           = 99999999999
    sh_path            = []
    new_exclude        = exclude . clone()
    new_exclude [from] = 1

    for step in 0 .. matrix . length() - 1 do
        if  step == from || step == to || exclude . key?(step) then
            next
        end

        length, path = shortest_path(matrix, step, to, new_exclude)
        if  shortest > length + matrix [from] [step] then
            shortest = length + matrix [from] [step]
            sh_path  = path . clone()
            sh_path . unshift (step)
        end
    end

    return shortest, sh_path
end

ARGF . each_line do
    |line|
    matrix . push (line . split(" ") . map {|x| x . to_i})
end

length, path = shortest_path(matrix, 0, 0, {})
puts (length)
puts (path . unshift(0) . join(" "))