import java.util.Scanner import scala.collection.mutable.ArrayBuffer object Problem228 { def proc(board: ArrayBuffer[ArrayBuffer[Int]]): String = { val answer = ArrayBuffer( ArrayBuffer(1, 2, 3, 4), ArrayBuffer(5, 6, 7, 8), ArrayBuffer(9, 10, 11, 12), ArrayBuffer(13, 14, 15, 0) ) val directions = List((-1, 0), (1, 0), (0, -1), (0, 1)) var fromRow = board.indexWhere(_.contains(0)) var fromCol = board(fromRow).indexOf(0) var toRow = -1 var toCol = -1 while (board != answer) { var canMoveToSomePlace = false for (direction <- directions) { toRow = fromRow + direction._1 toCol = fromCol + direction._2 if (moveIfCanMove(board, fromRow, fromCol, toRow, toCol)) { fromRow = toRow fromCol = toCol canMoveToSomePlace = true } } if (!canMoveToSomePlace) { return "No" } } "Yes" } def moveIfCanMove(board: ArrayBuffer[ArrayBuffer[Int]], fromRow: Int, fromCol: Int, toRow: Int, toCol: Int): Boolean = { def inBoard(row: Int, col: Int): Boolean = { row >= 0 && row < 4 && col >= 0 && col < 4 } val canMove = inBoard(fromRow, fromCol) && inBoard(toRow, toCol) && board(toRow)(toCol) == fromRow * 4 + fromCol + 1 if(canMove){ val swap = board(fromRow)(fromCol) board(fromRow)(fromCol) = board(toRow)(toCol) board(toRow)(toCol) = swap } canMove } def main(args: Array[String]) { val sc = new Scanner(System.in) val board = ArrayBuffer.fill(4, 4)(sc.nextInt) val result = proc(board) println(result) } }