#!/usr/bin/ruby # Find all whitespaces reachable from upper left corner and mark them # with decimal digits. # Load input maze = [] ARGF.each_line{|line| maze.push(line)} height = maze.size if height <= 0 puts "Emtpy input" exit 1 end if maze[0][0] != ' ' puts "Upper left corner is not whitespace" exit 1 end # Breadth-first expansion. visited = {} visit_queue = [[0, 0, 0]] while visit_queue.size > 0 y, x, d = visit_queue.shift if y < 0 || y >= height || x < 0 || maze[y][x] != ' ' next end key = [y, x] if visited[key] next end # Mark current cell as reachable and record distance to reach it visited[key] = d # Expand neighbors [[-1, 0], [1, 0], [0, -1], [0, 1]].each{|dy, dx| visit_queue.push([y + dy, x + dx, d + 1]) } end # Mark distances visited.each{|p, d| maze[p[0]][p[1]] = ((d % 10) + '0'.ord).chr } maze.each{|line| puts line}