Skip to content

Commit

Permalink
0051.N皇后 调整Java代码和Python代码的顺序,修改为与其它题解顺序一致
Browse files Browse the repository at this point in the history
  • Loading branch information
fengxiuyang authored Apr 10, 2022
1 parent 6553b5b commit b6633fe
Showing 1 changed file with 51 additions and 50 deletions.
101 changes: 51 additions & 50 deletions problems/0051.N皇后.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,56 +224,6 @@ public:

## 其他语言补充


### Python

```python
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
if not n: return []
board = [['.'] * n for _ in range(n)]
res = []
def isVaild(board,row, col):
#判断同一列是否冲突
for i in range(len(board)):
if board[i][col] == 'Q':
return False
# 判断左上角是否冲突
i = row -1
j = col -1
while i>=0 and j>=0:
if board[i][j] == 'Q':
return False
i -= 1
j -= 1
# 判断右上角是否冲突
i = row - 1
j = col + 1
while i>=0 and j < len(board):
if board[i][j] == 'Q':
return False
i -= 1
j += 1
return True

def backtracking(board, row, n):
# 如果走到最后一行,说明已经找到一个解
if row == n:
temp_res = []
for temp in board:
temp_str = "".join(temp)
temp_res.append(temp_str)
res.append(temp_res)
for col in range(n):
if not isVaild(board, row, col):
continue
board[row][col] = 'Q'
backtracking(board, row+1, n)
board[row][col] = '.'
backtracking(board, 0, n)
return res
```

### Java

```java
Expand Down Expand Up @@ -343,6 +293,55 @@ class Solution {
}
```

### Python

```python
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
if not n: return []
board = [['.'] * n for _ in range(n)]
res = []
def isVaild(board,row, col):
#判断同一列是否冲突
for i in range(len(board)):
if board[i][col] == 'Q':
return False
# 判断左上角是否冲突
i = row -1
j = col -1
while i>=0 and j>=0:
if board[i][j] == 'Q':
return False
i -= 1
j -= 1
# 判断右上角是否冲突
i = row - 1
j = col + 1
while i>=0 and j < len(board):
if board[i][j] == 'Q':
return False
i -= 1
j += 1
return True

def backtracking(board, row, n):
# 如果走到最后一行,说明已经找到一个解
if row == n:
temp_res = []
for temp in board:
temp_str = "".join(temp)
temp_res.append(temp_str)
res.append(temp_res)
for col in range(n):
if not isVaild(board, row, col):
continue
board[row][col] = 'Q'
backtracking(board, row+1, n)
board[row][col] = '.'
backtracking(board, 0, n)
return res
```


### Go
```Go
Expand Down Expand Up @@ -398,6 +397,8 @@ func isValid(n, row, col int, chessboard [][]string) bool {
return true
}
```


### Javascript
```Javascript
var solveNQueens = function(n) {
Expand Down

0 comments on commit b6633fe

Please sign in to comment.