1+ class Solution {
2+ public char [][] updateBoard (char [][] board , int [] click ) {
3+ int x = click [0 ];
4+ int y = click [1 ];
5+
6+ bfs (board , x , y );
7+ return board ;
8+ }
9+
10+ private void bfs (char [][] board , int x , int y ) {
11+ if (!checkBound (board , x , y )) {
12+ return ;
13+ }
14+ if (board [x ][y ] == 'M' ) {
15+ board [x ][y ] = 'X' ;
16+ return ;
17+ }
18+ int count = countMine (board , x , y );
19+ if (board [x ][y ] == 'E' ) {
20+ if (count == 0 ) {
21+ board [x ][y ] = 'B' ;
22+ bfs (board , x - 1 , y - 1 );
23+ bfs (board , x , y - 1 );
24+ bfs (board , x + 1 , y - 1 );
25+ bfs (board , x - 1 , y );
26+ bfs (board , x , y );
27+ bfs (board , x + 1 , y );
28+ bfs (board , x - 1 , y + 1 );
29+ bfs (board , x , y + 1 );
30+ bfs (board , x + 1 , y + 1 );
31+ } else {
32+ board [x ][y ] = (char ) (count + 48 );
33+ }
34+ }
35+ }
36+
37+ private int countMine (char [][] board , int x , int y ) {
38+ int count = 0 ;
39+ if (checkBound (board , x - 1 , y - 1 )) {
40+ if ('M' == board [x - 1 ][y - 1 ]) {
41+ count ++;
42+ }
43+ }
44+ if (checkBound (board , x , y - 1 )) {
45+ if ('M' == board [x ][y - 1 ]) {
46+ count ++;
47+ }
48+ }
49+ if (checkBound (board , x + 1 , y - 1 )) {
50+ if ('M' == board [x + 1 ][y - 1 ]) {
51+ count ++;
52+ }
53+ }
54+ if (checkBound (board , x - 1 , y )) {
55+ if ('M' == board [x - 1 ][y ]) {
56+ count ++;
57+ }
58+ }
59+ if (checkBound (board , x + 1 , y )) {
60+ if ('M' == board [x + 1 ][y ]) {
61+ count ++;
62+ }
63+ }
64+ if (checkBound (board , x - 1 , y + 1 )) {
65+ if ('M' == board [x - 1 ][y + 1 ]) {
66+ count ++;
67+ }
68+ }
69+ if (checkBound (board , x , y + 1 )) {
70+ if ('M' == board [x ][y + 1 ]) {
71+ count ++;
72+ }
73+ }
74+ if (checkBound (board , x + 1 , y + 1 )) {
75+ if ('M' == board [x + 1 ][y + 1 ]) {
76+ count ++;
77+ }
78+ }
79+ return count ;
80+ }
81+
82+ private boolean checkBound (char [][] board , int x , int y ) {
83+ return x >= 0 && y >= 0 && x < board .length && y < board [0 ].length ;
84+ }
85+ }
0 commit comments