|
| 1 | +/** |
| 2 | + * Question Link: https://leetcode.com/problems/minesweeper/ |
| 3 | + * Primary idea: Classic Depth-first Search. Check current node and dfs all directions if mine count is 0, update the board accordingly. |
| 4 | + * |
| 5 | + * Time Complexity: O(mn), Space Complexity: O(mn) |
| 6 | + * |
| 7 | + */ |
| 8 | + |
| 9 | +class Minesweeper { |
| 10 | + private let dirs = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1)] |
| 11 | + |
| 12 | + func updateBoard(_ board: [[Character]], _ click: [Int]) -> [[Character]] { |
| 13 | + let i = click[0], j = click[1] |
| 14 | + var board = board |
| 15 | + |
| 16 | + if board[i][j] == "M" { |
| 17 | + board[i][j] = "X".first! |
| 18 | + return board |
| 19 | + } |
| 20 | + |
| 21 | + let m = board.count, n = board[0].count |
| 22 | + var isVisited = Array(repeating: Array(repeating: false, count: n), count: m) |
| 23 | + |
| 24 | + dfs(&board, i, j, &isVisited) |
| 25 | + |
| 26 | + return board |
| 27 | + } |
| 28 | + |
| 29 | + private func dfs(_ board: inout [[Character]], _ i: Int, _ j: Int, _ isVisited: inout [[Bool]]) { |
| 30 | + guard isValid(i, j, board) && !isVisited[i][j] else { |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + isVisited[i][j] = true |
| 35 | + |
| 36 | + if board[i][j] == "E" { |
| 37 | + var count = 0 |
| 38 | + for dir in dirs { |
| 39 | + let x = i + dir.0, y = j + dir.1 |
| 40 | + |
| 41 | + if isValid(x, y, board) { |
| 42 | + if board[x][y] == "X" || board[x][y] == "M" { |
| 43 | + count += 1 |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + if count == 0 { |
| 49 | + board[i][j] = "B".first! |
| 50 | + |
| 51 | + for dir in dirs { |
| 52 | + let x = i + dir.0, y = j + dir.1 |
| 53 | + dfs(&board, x, y, &isVisited) |
| 54 | + } |
| 55 | + } else { |
| 56 | + board[i][j] = String(count).first! |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + private func isValid(_ i: Int, _ j: Int, _ board: [[Character]]) -> Bool { |
| 62 | + return i >= 0 && i < board.count && j >= 0 && j < board[0].count |
| 63 | + } |
| 64 | +} |
0 commit comments