import scala.io.StdIn object Solution { type State = (Vector[Int], List[Int]) def main(args: Array[String]): Unit = { val n = StdIn.readInt() val initialState = (Vector(0) ++ (0 until n * n - 1).map({ i => -1 }), List(0)) (1 until n) foreach { i => println((1 until n).map({ j => bfs(n, i, j, initialState)._1.last }).mkString(" ")) } } def bfs(n: Int, a: Int, b: Int, state: State): State = state._2 match { case Nil => state case c :: cs => { if (state._1.last > -1) state else { val d = state._1(c) val newCells = neighbours(n, a, b, c).filter(i => state._1(i) == -1) val updatedBoard = newCells.foldLeft(state._1)((b, cell) => b.updated(cell, d + 1)) bfs(n, a, b, (updatedBoard, cs ++ newCells)) } } } def neighbours(n: Int, a: Int, b: Int, cell: Int): Set[Int] = { val x = cell / n val y = cell % n Set( (x - a, y - b), (x - a, y + b), (x + a, y - b), (x + a, y + b), (x - b, y - a), (x - b, y + a), (x + b, y - a), (x + b, y + a) ).filter(cell => cell._1 >= 0 && cell._1 < n && cell._2 >= 0 && cell._2 < n).map(cell => cell._1 * n + cell._2) } }