Created
December 12, 2022 17:52
-
-
Save cjavdev/37aa7385afb395147d67dd922de21808 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if ARGV.empty? | |
data = DATA.readlines(chomp: true) | |
else | |
data = File.readlines(ARGV[0], chomp: true) | |
end | |
grid = data.map(&:chars) | |
heights = Array.new(grid.size) { Array.new(grid[0].size) } | |
distances = {} | |
neighbors = [] | |
e = nil | |
grid.each_with_index do |row, x| | |
row.each_with_index do |cell, y| | |
# if cell == 'S' # part 1 | |
if cell == 'S' || cell == 'a' | |
heights[x][y] = 1 | |
distances[[x, y]] = 0 | |
neighbors << [x, y] | |
elsif cell == 'E' | |
heights[x][y] = 26 | |
e = [x, y] | |
else | |
heights[x][y] = cell.ord - 'a'.ord + 1 | |
end | |
end | |
end | |
until neighbors.empty? | |
x, y = neighbors.shift | |
distance = distances[[x, y]] | |
[[0, 1], [0, -1], [1, 0], [-1, 0]].each do |dx, dy| | |
nx, ny = x + dx, y + dy | |
if nx.between?(0, grid.size - 1) && ny.between?(0, grid.first.size - 1) && | |
heights[nx][ny] <= heights[x][y] + 1 | |
if distances[[nx, ny]].nil? || distances[[nx, ny]] > distance + 1 | |
neighbors << [nx, ny] | |
distances[[nx, ny]] = distance + 1 | |
end | |
end | |
end | |
end | |
p distances[e] | |
__END__ | |
Sabqponm | |
abcryxxl | |
accszExk | |
acctuvwj | |
abdefghi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://youtu.be/Klp6NKEXiw8