#!/bin/ruby n = gets.strip.to_i size = n - 1 solution = Array.new(size) { Array.new(size)} # your code goes here for i in 1..size for j in i..size board = Array.new(n) { Array.new(n)} moves = [[i,j], [i,-j], [-i,j], [-i,-j], [j,i], [j,-i], [-j,i], [-j,-i]] lastIter= Array.new lastIter.push [0,0] iter = 0; board[0][0] = iter done = false loop do nextIter= Array.new iter = iter + 1 for pos in lastIter for m in moves px = pos[0] + m[0] py = pos[1] + m[1] if (0..size) === px && (0..size) === py && !board[px][py] board[px][py] = iter nextIter.push [px, py] done = px == size && py == size end break if done end break if done end lastIter = nextIter break if nextIter.empty? || done end if done solution[i-1][j-1] = iter solution[j-1][i-1] = iter else solution[i-1][j-1] = -1 solution[j-1][i-1] = -1 end end end for i in 0..(solution.size-1) puts solution[i].join(' ') end