Simple Python using stack


  • 0

    Pretty straight forward one.

    class Solution(object):
        def updateBoard(self, board, click):
            """
            :type board: List[List[str]]
            :type click: List[int]
            :rtype: List[List[str]]
            """
            if board[click[0]][click[1]] == "M":
                board[click[0]][click[1]] = "X"
                return board
            m, n = len(board), len(board[0]) if board else 0
            stack = [click]
            visited = set()
            while stack:
                i, j = stack.pop()
                if (i, j) in visited: continue
                visited.add((i, j))
                neighs = [(x, y) for x, y in ((i+1, j+1), (i+1,j), (i+1,j-1), (i,j+1), \
                          (i, j), (i, j-1), (i-1, j+1), (i-1, j), (i-1, j-1)) \
                          if -1<x<m and -1<y<n]
                num = sum(board[x][y] == "M" for x,y in neighs)
                board[i][j] = str(num) if num else "B"
                if not num:
                    stack.extend(neighs)
            return board
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.