From 371564ba3b9a2b9641cafc05eb033f8d162aec81 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Tue, 7 Jun 2022 22:19:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200051.N=E7=9A=87=E5=90=8E.m?= =?UTF-8?q?d=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 74 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index c03e48c2..f65ccaf5 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -455,7 +455,7 @@ var solveNQueens = function(n) { }; ``` -## TypeScript +### TypeScript ```typescript function solveNQueens(n: number): string[][] { @@ -683,5 +683,77 @@ char *** solveNQueens(int n, int* returnSize, int** returnColumnSizes){ } ``` +### Scala + +```scala +object Solution { + import scala.collection.mutable + def solveNQueens(n: Int): List[List[String]] = { + var result = mutable.ListBuffer[List[String]]() + + def judge(x: Int, y: Int, maze: Array[Array[Boolean]]): Boolean = { + // 正上方 + var xx = x + while (xx >= 0) { + if (maze(xx)(y)) return false + xx -= 1 + } + // 左边 + var yy = y + while (yy >= 0) { + if (maze(x)(yy)) return false + yy -= 1 + } + // 左上方 + xx = x + yy = y + while (xx >= 0 && yy >= 0) { + if (maze(xx)(yy)) return false + xx -= 1 + yy -= 1 + } + xx = x + yy = y + // 右上方 + while (xx >= 0 && yy < n) { + if (maze(xx)(yy)) return false + xx -= 1 + yy += 1 + } + true + } + + def backtracking(row: Int, maze: Array[Array[Boolean]]): Unit = { + if (row == n) { + // 将结果转换为题目所需要的形式 + var path = mutable.ListBuffer[String]() + for (x <- maze) { + var tmp = mutable.ListBuffer[String]() + for (y <- x) { + if (y == true) tmp.append("Q") + else tmp.append(".") + } + path.append(tmp.mkString) + } + result.append(path.toList) + return + } + + for (j <- 0 until n) { + // 判断这个位置是否可以放置皇后 + if (judge(row, j, maze)) { + maze(row)(j) = true + backtracking(row + 1, maze) + maze(row)(j) = false + } + } + } + + backtracking(0, Array.ofDim[Boolean](n, n)) + result.toList + } +} +``` + -----------------------