import scala.util._

def print_board(n: Int)(steps: List[(Int, Int)]): Unit = {
  for (i <- 0 until n) {
    for (j <- 0 until n) {
      print(f"${steps.indexOf((i, j))}%3.0f ")
    }
    println
  } 
  //readLine()
  //System.exit(0)
  throw new Exception("\n")
}

def add_pair(x: (Int, Int))(y: (Int, Int)) = 
  (x._1 + y._1, x._2 + y._2)

def is_legal(n: Int)(x: (Int, Int)) = 
  0 <= x._1 && 0 <= x._2 && x._1 < n && x._2 < n

def moves(n: Int)(x: (Int, Int)): List[(Int, Int)] = {
  List((1, 2),(2, 1),(2, -1),(1, -2),
       (-1, -2),(-2, -1),(-2, 1),(-1, 2)).map(add_pair(x)).filter(is_legal(n))
}

def ordered_moves(n: Int)(steps: List[(Int, Int)])(x : (Int, Int)): List[(Int, Int)] = 
  moves(n)(x).sortBy((x: (Int, Int)) => moves(n)(x).filterNot(steps.contains(_)).length)

moves(8)(1,3)
ordered_moves(8)(Nil)(1,3)
ordered_moves(8)(List((2, 4), (2, 6)))(1,3)

// non-circle tour parallel
def tour(n: Int)(steps: List[(Int, Int)]): Unit = {
  if (steps.length ==  n * n)
    print_board(n)(steps)
  else 
    for (x <- moves(n)(steps.head); if (!steps.contains(x))) tour(n)(x :: steps)
}

// non-circle tour
def ctour(n: Int)(steps: List[(Int, Int)]): Unit = {
  if (steps.length ==  n * n && moves(n)(steps.head).contains(steps.last))
    print_board(n)(steps)
  else 
    for (x <- moves(n)(steps.head); if (!steps.contains(x))) ctour(n)(x :: steps)
}


def faster_tour(n: Int)(steps: List[(Int, Int)]): Unit = {
  if (steps.length ==  n * n && moves(n)(steps.head).contains(steps.last))
    print_board(n)(steps)
  else 
    for (x <- ordered_moves(n)(steps)(steps.head); if (!steps.contains(x))) faster_tour(n)(x :: steps)
}


val n1 = 5
println(s"simple tour: n = $n1")

Try {
  for (i <- 0 until n1; j <- 0 until n1) {
    tour(n1)(List((i, j))) 
  }
}


val n2 = 6
println(s"circle tour: n = $n2")

Try {
  for (i <- 0 until n2; j <- 0 until n2) {
    ctour(n2)(List((i, j))) 
  }
}


val n3 = 8
println(s"fast circle tour: n = $n3")

Try {
  for (i <- 0 until n3; j <- 0 until n3) {
    faster_tour(n3)(List((i, j))) 
  }
}

println("finished")
