#!/bin/ruby N = gets.strip.to_i # your code goes here def in_board?(pos) x, y = pos x < N && y < N && x > -1 && y > -1 end def find_path(a, b) start = [0, 0] finish = [N - 1, N - 1] moves = [[a, b], [-1 * a, -1 * b], [-1 * a, b], [a, -1 * b], [b, a], [-1 * b, -1 * a], [-1 * b, a], [b, -1 * a]].uniq dist = {} dist[start] = 0 queue = Queue.new queue << start until queue.empty? cur = queue.pop return dist[cur] if cur == finish moves.each do |move| next_pos = [cur[0] + move[0], cur[1] + move[1]] next unless in_board?(next_pos) next if dist[next_pos] dist[next_pos] = dist[cur] + 1 queue << next_pos end end -1 end diffs = [] 1.upto(N - 1).each do |a| 1.upto(N - 1).each do |b| diffs << [a, b] end end diffs.each.with_index do |diff, idx| a, b = diff print find_path(a, b) print (idx + 1) % (N - 1) == 0 ? "\n" : ' ' end