编程语言
首页 > 编程语言> > [leetcode] 529. Minesweeper @ python

[leetcode] 529. Minesweeper @ python

作者:互联网

原题

https://leetcode.com/problems/minesweeper/

解法

DFS. Base case是board为空时, 返回[]. 定义DFS函数, base case是当前位置的值不是’E’, 直接返回. 我们先计算click位置的相邻位置有多少个’M’, 将click位置更新, 注意: 如果click位置更新的是数字的话, 我们就不再对它相邻的’E’进行reveal, 直接return. 如果click位置更新的是’B’的话, 我们用DFS进行递归.

代码

class Solution:
    def updateBoard(self, board, click):
        """
        :type board: List[List[str]]
        :type click: List[int]
        :rtype: List[List[str]]
        """ 
        # base case:
        if not board: 
            return []        
        
        x, y = click[0], click[1]
        # If a mine ('M') is revealed, then the game is over 
        if board[x][y] == 'M':
            board[x][y] = 'X'
            return board
        # keep revealing the board unitl no more squares will be revealed
        self.dfs(board, x, y)
        return board
        
    def dfs(self, board, x, y):        
        # edge case
        if board[x][y] != 'E':
            return
        row, col = len(board), len(board[0])
        directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)]
        count = 0
        for (dx, dy) in directions:
            if 0 <= x+dx < row and 0 <= y+dy < col and board[x+dx][y+dy] == 'M':
                count += 1
        if count == 0:
            board[x][y] = 'B'
        else:
            board[x][y] = str(count)
            return 
            
        for dx, dy in directions:
            if 0 <= x+dx < row and 0 <= y+dy < col:
                self.dfs(board, x+dx, y+dy)
                

标签:case,return,python,Minesweeper,self,List,leetcode,board,click
来源: https://blog.csdn.net/danspace1/article/details/86607795