总结:和第1020道题目很相似,不过自己照着前面那道的题目的思路来并没有解决问题,这和自己没有完全理解题目意思也有一定关系,题目的意思是只要一片区域内有一个和边界相交的话这一片区域都是不用变成'X'的,自己利用之前的思路不能做到bug free,看完题解后觉得真妙,并没有设置利用visited数组,而是直接先从四个边界判断起,边界中如果有为'O'的地方,则利用广搜或者深搜搜索出这一片区域则这一片区域都是不用改变,其余的再根据题意改成'X'即可。
代码:
- class Solution {
- public:
- int dir[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1};
- void dfs(vector
char >>& board, int x,int y) - {
- board[x][y] = 'A';
- for(int i = 0;i < 4;i++)
- {
- int nextx = x + dir[i][0];
- int nexty = y + dir[i][1];
- if (nextx < 0 || nextx >= board.size() || nexty < 0 || nexty >= board[0].size()) continue;
- if(board[nextx][nexty] == 'X' || board[nextx][nexty] == 'A') continue;
-
- dfs (board, nextx, nexty);
- }
- return;
- }
- void solve(vector
char >>& board) { - int n = board.size();
- int m = board[0].size();
- for(int i = 0;i < n;i++)
- {
- if(board[i][0] == 'O') dfs(board,i, 0);
- if(board[i][m - 1] == 'O') dfs(board, i, m - 1);
- }
- for (int j = 0; j < m; j++) {
- if (board[0][j] == 'O') dfs(board, 0, j);
- if (board[n - 1][j] == 'O') dfs(board, n - 1, j);
- }
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++) {
- if (board[i][j] == 'O') board[i][j] = 'X';
- if (board[i][j] == 'A') board[i][j] = 'O';
- }
- }
-
- }
- };