https://leetcode-cn.com/problems/minesweeper/solution/python3-dfsbfszhu-shi-by-xxd630/
規則:python
邊界條件:app
若是click是'M',那麼就是踩雷了設定爲X退出,返回棋盤。
若是不是分別進入DFS和BFScode
class SolutionDFS: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: if not board: return [] m,n=len(board),len(board[0]) i,j=click[0],click[1] if board[i][j] == 'M': board[i][j] = 'X' return board self.dfs(board,i,j) return board def dfs(self,board,i,j): if board[i][j] != 'E': return m,n=len(board),len(board[0]) directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)] mine_count = 0 for d in directions: ni,nj=i+d[0],j+d[1] if 0<=ni<m and 0<=nj<n and board[ni][nj]=='M': mine_count+=1 if mine_count == 0: board[i][j] = 'B' else: board[i][j] = str(mine_count) return for d in directions: ni,nj=i+d[0],j+d[1] if 0 <= ni <m and 0<=nj<n: self.dfs(board,ni,nj)
class SolutionBFS: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: m,n=len(board),len(board[0]) i,j=click[0],click[1] if board[i][j] == "M": board[i][j] = "X" directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)] import collections q = collections.deque() q.append(click) visited = set(click) def numBombs(board,i,j): mine_count = 0 for d in directions: ni, nj = i + d[0], j + d[1] if 0<=ni<m and 0<=nj<n and board[ni][nj] == 'M': mine_count+=1 return mine_count while q: for _ in range(len(q)): x,y=q.popleft() if board[x][y] == 'E': bombsNextTo = numBombs(board,x,y) board[x][y] = "B" if bombsNextTo == 0 else str(bombsNextTo) if bombsNextTo == 0: for d in directions: ni, nj = x + d[0], y + d[1] if 0<=ni<m and 0<=nj<n and (ni,nj) not in visited: q.append((ni,nj)) visited.add((ni,nj)) return board