51. N 皇后
题目链接:51. N 皇后
这题想到回溯算法就不难,但是is_vailed函数 比较难想到。
class Solution:
def __init__(self):
self.res=[]
def solveNQueens(self, n: int) :
Chreerboard=[['.' for _ in range(n)]for _ in range(n) ]
self.backtrACKING(Chreerboard,n,0)
return self.res
def backtrACKING(self,Chreerboard,n,row):
if row==n:
self.res.append([''.join(i) for i in Chreerboard])
return
#每一列中
def isvaild(board,row,col):
for i in range(len(board)):
if board[i][col]=='Q':
return False
# 排除自己本身
i=row-1
j=col-1
# 排除45度
while j>=0 and i>=0:
if board[i][j]=='Q':
return False
j-=1
i-=1
i=row-1
j=col+1
# 排除135度
while i>=0 and j<len(board):
if board[i][j] == 'Q':
return False
i-=1
j+=1
return True
#遍历每一列
for col in range(n):
if not isvaild(Chreerboard,row,col):
continue
Chreerboard[row][col]='Q'
self.backtrACKING(Chreerboard,n,row+1)
Chreerboard[row][col]='.'
37. 解数独
题目链接:37. 解数独
这题的思想还是要琢磨一下
class Solution:
def solveSudoku(self, board) -> None:
self.backtracking(board)
def backtracking(self,board):
for i in range (len(board)):
for j in range(len(board[0])):
if board[i][j] != '.': continue
for k in range(1,10):
if self.isvaild(i,j,k,board):
board[i][j]=str(k)
if self.backtracking(board):return True
board[i][j]= '.'
return False
return True
def isvaild(self,row,col,val,board):
# 行
for i in range(9):
if board[row][i]==str(val):
return False
# 列
for j in range(9):
if board[j][col]==str(val):
return False
# 九宫格
start_row=(row//3)*3
start_col=(col//3)*3
for i in range(start_row,start_row+3):
for j in range(start_col,start_col+3):
if board[i][j]==str(val):
return False
return True