#!/bin/ruby n = gets.strip.to_i Node = Struct.new(:pos, :moves) def knightl(n, a, b) start = [0, 0] q = [Node.new(start, 0)] marked = [] n.times { marked << [] } marked[0][0] = true until q.empty? current = q.shift r, c = current.pos if current.pos == [n - 1, n - 1] return current.moves end marked[r][c] = true [ [r + a, c + b], [r - a, c + b], [r + a, c - b], [r - a, c - b] ].each do |(x, y)| if x >= 0 && x < n && y >= 0 && y < n && !marked[x][y] marked[x][y] = true marked[y][x] = true q << Node.new([x, y], current.moves + 1) q << Node.new([y, x], current.moves + 1) end end end -1 end (1...n).each do |i| output = [] (1...n).each do |j| output << knightl(n, i, j) end puts output.join(' ') end