27
27
28
28
using namespace std ;
29
29
30
+ int di[] = {-1 , 1 , 0 , 0 };
31
+ int dj[] = {0 , 0 , -1 , 1 };
32
+
30
33
class Solution {
31
34
public:
32
35
void solve (vector<vector<char >> &board) {
33
36
if (board.empty () || board[0 ].empty ()) return ;
34
37
int M = board.size (), N = board[0 ].size ();
35
- for (int j = 0 ; j < N; j++) {
36
- if (board[0 ][j] == ' O' ) bfs (board, M, N, 0 , j);
37
- if (board[M - 1 ][j] == ' O' ) bfs (board, M, N, M - 1 , j);
38
- }
39
38
for (int i = 0 ; i < M; i++) {
40
39
if (board[i][0 ] == ' O' ) bfs (board, M, N, i, 0 );
41
- if (board[i][N - 1 ] == ' O' ) bfs (board, M, N, i, N - 1 );
40
+ if (board[i][N- 1 ] == ' O' ) bfs (board, M, N, i, N- 1 );
42
41
}
42
+ for (int j = 0 ; j < N; j++) {
43
+ if (board[0 ][j] == ' O' ) bfs (board, M, N, 0 , j);
44
+ if (board[M-1 ][j] == ' O' ) bfs (board, M, N, M-1 , j);
45
+ }
46
+
43
47
for (int i = 0 ; i < M; i++) {
44
48
for (int j = 0 ; j < N; j++) {
45
- if (board[i][j] == ' O ' ) board[i][j] = ' X ' ;
46
- else if (board[i][j] == ' D ' ) board[i][j] = ' O ' ;
49
+ if (board[i][j] == ' D ' ) board[i][j] = ' O ' ;
50
+ else if (board[i][j] == ' O ' ) board[i][j] = ' X ' ;
47
51
}
48
52
}
49
53
}
50
54
51
55
void bfs (vector<vector<char >> &board, int M, int N, int i, int j) {
56
+ board[i][j] = ' D' ;
52
57
queue<int > qs;
53
- board[i][j] = ' D ' , qs.push (i*N + j);
58
+ qs.push (i*N+ j);
54
59
while (!qs.empty ()) {
55
- i = qs.front () / N, j = qs.front () % N, qs.pop ();
56
- if (i - 1 >= 0 && board[i - 1 ][j] == ' O' ) board[i - 1 ][j] = ' D' , qs.push ((i - 1 )*N + j);
57
- if (i + 1 < M && board[i + 1 ][j] == ' O' ) board[i + 1 ][j] = ' D' , qs.push ((i + 1 )*N + j);
58
- if (j - 1 >= 0 && board[i][j - 1 ] == ' O' ) board[i][j - 1 ] = ' D' , qs.push (i*N + j - 1 );
59
- if (j + 1 < N && board[i][j + 1 ] == ' O' ) board[i][j + 1 ] = ' D' , qs.push (i*N + j + 1 );
60
+ i = qs.front ()/N, j = qs.front ()%N;
61
+ qs.pop ();
62
+ for (int k = 0 ; k < 4 ; k++) {
63
+ int ni = i+di[k], nj = j+dj[k];
64
+ if (ni == -1 || ni == M || nj == -1 || nj == N || board[ni][nj] != ' O' ) continue ;
65
+ board[ni][nj] = ' D' ;
66
+ qs.push (ni*N+nj);
67
+ }
60
68
}
61
69
}
62
70
};
@@ -91,4 +99,4 @@ int main() {
91
99
}
92
100
93
101
return 0 ;
94
- }
102
+ }
0 commit comments