Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加(0051.N皇后.md)Scala版本 #1451

Merged
merged 1 commit into from
Jul 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 73 additions & 1 deletion problems/0051.N皇后.md
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ var solveNQueens = function(n) {
};
```

## TypeScript
### TypeScript

```typescript
function solveNQueens(n: number): string[][] {
Expand Down Expand Up @@ -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>