mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0051.N皇后.md Scala版本
This commit is contained in:
@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user