Skip to content

Instantly share code, notes, and snippets.

@waynejo
Last active May 24, 2019 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waynejo/575c4e566a3020b0f311fb7ddf9a2aa4 to your computer and use it in GitHub Desktop.
Save waynejo/575c4e566a3020b0f311fb7ddf9a2aa4 to your computer and use it in GitHub Desktop.
import scala.io.StdIn
import scala.util.Random
object Solution extends App {
def solve(w: Int, h: Int): Option[Vector[(Int, Int)]] = {
val map = Array.ofDim[Boolean](h, w)
def _trace(lastPoint: (Int, Int), acc: Vector[(Int, Int)], remains: Vector[Int]): Option[Vector[(Int, Int)]] = {
if (remains.isEmpty) {
Some(acc)
} else {
for (pos <- remains) {
val newX = pos % w
val newY = pos / w
val x = lastPoint._1
val y = lastPoint._2
if (x != newX && y != newY && y - x != newY - newX && y + x != newY + newX && !map(newY)(newX)) {
map(newY)(newX) = true
_trace((newX, newY), (newX, newY) +: acc, remains.filter(_ != pos)) match {
case Some(result) =>
return Some(result)
case _ =>
}
map(newY)(newX) = false
}
}
None
}
}
map(0)(0) = true
_trace((0, 0), Vector((0, 0)), Random.shuffle((1 until (w * h)).toVector))
}
val cases = StdIn.readLine().toInt
(1 to cases) foreach { i => {
val Array(h, w) = StdIn.readLine().split(" ").map(_.toInt)
val answer = solve(h, w)
answer match {
case Some(x) =>
println(s"Case #$i: POSSIBLE")
println(x.map(k => s"${k._1 + 1} ${k._2 + 1}").mkString("\n"))
case _ =>
println(s"Case #$i: IMPOSSIBLE")
}
}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment