Skip to content

Instantly share code, notes, and snippets.

@whatalnk
Created February 19, 2018 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whatalnk/2bcb1ed08f6db5f225acd9a655841d6f to your computer and use it in GitHub Desktop.
Save whatalnk/2bcb1ed08f6db5f225acd9a655841d6f to your computer and use it in GitHub Desktop.
AtCoder ABC 088 D. Grid Repainting
H, W = gets.chomp.split(" ").map(&:to_i)
$grid = []
blk = 0
H.times do
row = gets.chomp.split("")
row.each do |c|
blk += 1 if c == "#"
end
$grid << row
end
INF = 10**9
$d = Array.new(H + 1){Array.new(W + 1, INF)}
$dx = [1, 0, -1, 0]
$dy = [0, 1, 0, -1]
def bfs()
que = []
que << [0, 0]
$d[0][0] = 0
while !que.empty?
pos = que.shift
break if pos[0] == H - 1 && pos[1] == W - 1
4.times do |i|
nx = pos[0] + $dx[i]
ny = pos[1] + $dy[i]
if 0 <= nx && nx < W && 0 <= ny && ny < H && $grid[ny][nx] != "#" && $d[ny][nx] == INF then
que << [nx, ny]
$d[ny][nx] = $d[pos[1]][pos[0]] + 1
end
end
end
return $d[H-1][W-1]
end
res = bfs()
if res == INF then
puts -1
else
puts H * W - blk - (res + 1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment