Mine Sweeper

此题注意理解题意,因为描述比较长,这里说的是九边有雷的位置就不能再往前搜索了,如果没有雷则可以继续推进,另外这里要注意,用BFS做这道题时,如果同时搜索雷数和四边的点会产生一个错误,即如果此点的九边是有雷的,则我们不能把这个点四周符合条件的点放进去,所以BFS时需要一个临时数组先把待搜索的点放进去,最后在检查是否有雷时再加入队列中,另外BFS做这道题如果不用你查重矩阵的话会有很多重复点进入队列,效率肯定没有DFS高

class Solution(object):
    def updateBoard(self, board, click):
        """
        :type board: List[List[str]]
        :type click: List[int]
        :rtype: List[List[str]]
        """
        n = len(board)
        if not n:
            return []

        m = len(board[0])
        if not m:
            return []

        row, col = click
        if board[row][col] == 'M':
            board[row][col] = 'X'
            return board

        queue = collections.deque([(row, col, )])
        while queue:
            row, col = queue.pop()
            mines = 0
            tmp = []
            for i, j in [[0, 1], [0, -1], [1, 0], [1, -1], [1, 1], [-1, 0], [-1, -1], [-1, 1]]:
                curRow, curCol = row + i, col + j
                if 0 <= curRow < n and 0 <= curCol < m:
                    if board[curRow][curCol] == 'E':
                        tmp.append((curRow, curCol,))
                    if board[curRow][curCol] == 'M':
                        mines += 1

            if mines:
                board[row][col] = `mines`
            else:
                board[row][col] = 'B'
                queue += tmp

        return board

results matching ""

    No results matching ""