Created
September 6, 2017 14:53
-
-
Save cixuuz/0db7f5d801bf6c49b2345e643e91d50b to your computer and use it in GitHub Desktop.
[529. Minesweeper] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| // O(9^n) O(1) | |
| public char[][] updateBoard(char[][] board, int[] click) { | |
| int m = board.length; | |
| int n = board[0].length; | |
| if (click.length < 2) return board; | |
| int i = click[0]; | |
| int j = click[1]; | |
| if (board[i][j] == 'M') { | |
| board[i][j] = 'X'; | |
| return board; | |
| } | |
| revealBoard(board, m, n, i, j); | |
| return board; | |
| } | |
| private void revealBoard(char[][] board, int m, int n, int i, int j) { | |
| if (i < 0 || i >= m || j < 0 || j >= n) return; | |
| if (board[i][j] != 'E') return; | |
| int count = 0; | |
| for (int bi = -1; bi <= 1; bi++) { | |
| for (int bj = -1; bj <= 1; bj++) { | |
| if (bi == 0 && bj == 0) continue; | |
| count += countMines(board, m, n, i+bi, j+bj); | |
| } | |
| } | |
| if (count == 0) { | |
| board[i][j] = 'B'; | |
| for (int bi = -1; bi <= 1; bi++) { | |
| for (int bj = -1; bj <= 1; bj++) { | |
| if (bi == 0 && bj == 0) continue; | |
| revealBoard(board, m, n, i+bi, j+bj); | |
| } | |
| } | |
| } else { | |
| board[i][j] = Character.forDigit(count, 10); | |
| } | |
| } | |
| private int countMines(char[][] board, int m, int n, int i, int j) { | |
| if (i < 0 || i >= m || j < 0 || j >= n) return 0; | |
| if (board[i][j] == 'M') return 1; | |
| return 0; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment