#!/bin/ruby n = gets.strip.to_i # your code goes here require 'pp' def check_and_move(n, x, y, a, b, next_val, map, queue) next_x = x + a next_y = y + b return unless next_x >= 0 && next_x < n && next_y >=0 && next_y < n if map[next_x][next_y].nil? || map[next_x][next_y] > next_val map[next_x][next_y] = next_val queue.push([next_x, next_y]) end end def search(n, a, b) map = [] n.times { map << [nil] * n } queue = [[0,0]] while !queue.empty? #pp map x, y = queue.shift next_val = map[x][y].to_i + 1 #puts "x:#{x} y:#{y} next_val:#{next_val}" check_and_move(n, x, y, a, b, next_val, map, queue) check_and_move(n, x, y, -a, b, next_val, map, queue) check_and_move(n, x, y, a, -b, next_val, map, queue) check_and_move(n, x, y, -a, -b, next_val, map, queue) if a != b check_and_move(n, x, y, b, a, next_val, map, queue) check_and_move(n, x, y, -b, a, next_val, map, queue) check_and_move(n, x, y, b, -a, next_val, map, queue) check_and_move(n, x, y, -b, -a, next_val, map, queue) end end #pp map ret = map[n-1][n-1] ret ? ret : -1 end #puts search(n, 1, 2) #exit 0 def main(n) ary = [] n.times{ ary.push([])} 1.upto(n-1) do |a| 1.upto(n-1) do |b| next if ary[a][b] ary[a][b] = ary[b][a] = search(n, a, b) end end 1.upto(n-1) do |a| 1.upto(n-1) do |b| v = ary[a][b] v = -1 if v.nil? print "#{v} " end puts end end main(n)