|
| 1 | +# Source : https://leetcode.com/problems/minesweeper/?tab=Description |
| 2 | +# Author : Han Zichi |
| 3 | +# Date : 2017年03月07日 |
| 4 | + |
| 5 | +class Solution(object): |
| 6 | + def updateBoard(self, board, click): |
| 7 | + """ |
| 8 | + :type board: List[List[str]] |
| 9 | + :type click: List[int] |
| 10 | + :rtype: List[List[str]] |
| 11 | + """ |
| 12 | + n, m = len(board), len(board[0]) |
| 13 | + dir = [[1, 0], [-1, 0], [0, 1], [0, -1], [-1, -1], [-1, 1], [1, -1], [1, 1]] |
| 14 | + |
| 15 | + def isNotInMap(x, y): |
| 16 | + return x < 0 or x >= n or y < 0 or y >= m |
| 17 | + |
| 18 | + def getMineNum(x, y): |
| 19 | + num = 0 |
| 20 | + for i in range(8): |
| 21 | + _x, _y = x + dir[i][0], y + dir[i][1] |
| 22 | + if isNotInMap(_x, _y): |
| 23 | + continue |
| 24 | + if board[_x][_y] == 'M': |
| 25 | + num += 1 |
| 26 | + if num == 0: |
| 27 | + return 'B' |
| 28 | + else: |
| 29 | + return str(num) |
| 30 | + |
| 31 | + def dfs(x, y): |
| 32 | + if board[x][y] == 'M': |
| 33 | + board[x][y] = 'X' |
| 34 | + else: |
| 35 | + board[x][y] = getMineNum(x, y) |
| 36 | + if board[x][y] == 'B': |
| 37 | + for i in range(8): |
| 38 | + _x, _y = x + dir[i][0], y + dir[i][1] |
| 39 | + if isNotInMap(_x, _y): |
| 40 | + continue |
| 41 | + if board[_x][_y] != 'E': # not an empty cell |
| 42 | + continue |
| 43 | + dfs(_x, _y) |
| 44 | + |
| 45 | + dfs(click[0], click[1]) |
| 46 | + return board |
0 commit comments