classSolution: deftotalNQueens(self, n: int) -> int: chessboard = [[0]*n for i inrange(n)] self.res = 0
defis_valid(r,c): for i inrange(n): # 垂直 if chessboard[i][c] == "Q" : returnFalse # 左上 if r - i >=0and c-i >=0and chessboard[ r - i ][ c - i ] == "Q": returnFalse # 右上 if r - i >=0and c + i< n and chessboard[ r - i ][ c + i ] == "Q": returnFalse returnTrue
defdfs(r): if r == n: self.res += 1 return for c inrange(n): if is_valid(r,c) : chessboard[r][c] = "Q" dfs(r+1) chessboard[r][c] = "0" dfs(0)
return self.res
1 2 3 4 5 6 7 8
現在才知道 if col + (row - r) < n and chessboard[r][col + (row - r)] == 'Q' : returnFalse if chessboard[r][col + (row - r)] == 'Q'and col + (row - r) < n : returnFalse 有差 上方的的因為前辦已經false,所以不會跑超出範圍的 下方的可以因為超出範圍 先error,而不會達到想要的結果