diff --git "a/problems/0051.N\347\232\207\345\220\216.md" "b/problems/0051.N\347\232\207\345\220\216.md" index 7eb0d7a0b1..1b0cf0026b 100644 --- "a/problems/0051.N\347\232\207\345\220\216.md" +++ "b/problems/0051.N\347\232\207\345\220\216.md" @@ -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 @@ -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 @@ -398,6 +397,8 @@ func isValid(n, row, col int, chessboard [][]string) bool { return true } ``` + + ### Javascript ```Javascript var solveNQueens = function(n) {