-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.rb
110 lines (90 loc) · 2.18 KB
/
18.rb
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
#############################################################################
# 1
#############################################################################
lines = File.readlines('input18.txt')
map = []
71.times do
map << [0] * 71
end
lines[0..1023].each do |line|
x, y = line.scan(/\d+/).map(&:to_i)
map[y][x] = -1
end
paths = [[0, 0]]
cur_value = 1
map[0][0] = 1
loop do
new_paths = []
paths.each do |y, x|
if x < 70 && map[y][x + 1] == 0
map[y][x + 1] = cur_value + 1
new_paths << [y, x + 1]
end
if x > 0 && map[y][x - 1] == 0
map[y][x - 1] = cur_value + 1
new_paths << [y, x - 1]
end
if y < 70 && map[y + 1][x] == 0
map[y + 1][x] = cur_value + 1
new_paths << [y + 1, x]
end
if y > 0 && map[y - 1][x] == 0
map[y - 1][x] = cur_value + 1
new_paths << [y - 1, x]
end
end
break if new_paths.include?([70, 70])
paths = new_paths
cur_value += 1
end
puts cur_value
#############################################################################
# 2
#############################################################################
lines = File.readlines('input18.txt')
all_coords = lines.map { |line| line.scan(/\d+/).map(&:to_i) }
current_index = 1024
loop do
map = []
71.times do
map << [0] * 71
end
all_coords[0..current_index].each do |x, y|
map[y][x] = -1
end
paths = [[0, 0]]
cur_value = 1
map[0][0] = 1
found = true
loop do
new_paths = []
paths.each do |y, x|
if x < 70 && map[y][x + 1] == 0
map[y][x + 1] = cur_value + 1
new_paths << [y, x + 1]
end
if x > 0 && map[y][x - 1] == 0
map[y][x - 1] = cur_value + 1
new_paths << [y, x - 1]
end
if y < 70 && map[y + 1][x] == 0
map[y + 1][x] = cur_value + 1
new_paths << [y + 1, x]
end
if y > 0 && map[y - 1][x] == 0
map[y - 1][x] = cur_value + 1
new_paths << [y - 1, x]
end
end
break if new_paths.include?([70, 70])
if new_paths.empty?
found = false
break
end
paths = new_paths
cur_value += 1
end
break unless found
current_index += 1
end
puts all_coords[current_index].join(',')