529. Minesweeper
- Fizz Buzz Multithreaded python solution
题目描述
Let’s play the minesweeper game (Wikipedia, online game)!
You are given a 2D char matrix representing the game board. ‘M’ represents an unrevealed mine, ‘E’ represents an unrevealed empty square, ‘B’ represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit (‘1’ to ‘8’) represents how many mines are adjacent to this revealed square, and finally ‘X’ represents a revealed mine.
Now given the next click position (row and column indices) among all the unrevealed squares (‘M’ or ‘E’), return the board after revealing this position according to the following rules:
If a mine (‘M’) is revealed, then the game is over - change it to ‘X’.
If an empty square (‘E’) with no adjacent mines is revealed, then change it to revealed blank (‘B’) and all of its adjacent unrevealed squares should be revealed recursively.
If an empty square (‘E’) with at least one adjacent mine is revealed, then change it to a digit (‘1’ to ‘8’) representing the number of adjacent mines.
Return the board when no more squares will be revealed.
解析
就是编程实现扫雷游戏喽
class Solution(object):def updateBoard(self, board, click):""":type board: List[List[str]]:type click: List[int]:rtype: List[List[str]]"""if not board or not board[0]:return []i, j = click[0], click[1]if board[i][j] == "M":board[i][j] = "X"return boardm, n = len(board), len(board[0])directions = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]self.dfs(i, j, m, n, board, directions)return boarddef dfs(self, i, j, m, n, board, directions):if board[i][j] != "E":returnmine_count = 0for d in directions:di, dj = i+d[0], j+d[1]if 0<=di<m and 0<=dj<n and board[di][dj] == "M":mine_count += 1if mine_count == 0:board[i][j] = "B"else:board[i][j] = str(mine_count)returnfor d in directions:di, dj = i+d[0], j+d[1]if 0<=di<m and 0<=dj<n:self.dfs(di, dj, m, n, board, directions)
Reference
https://leetcode.com/problems/minesweeper/discuss/137802/Python-DFS-solution