leetcode: surrounded-regions
if(board.size()<=2||board[0].size()<=2) return; 这句代码不写感觉也不影响整个算法呀,但是没有这句话就会报堆栈溢出错误。
还有就是将 row 和 col 定义为类的变量时也会报堆栈溢出错误。
但是在VS上没有这两句也可以正常运行,感觉很蒙,请大神指点。
class Solution {
const int dir[4][2] = { -1,0,1,0,0,1,0,-1 };
public:
void solve(vector<vector<char>> &board)
{
int row = board.size(); // 1
int col = board[0].size(); //2
if(board.size()<=2||board[0].size()<=2) return; //3
for (int i = 0;i<row;i++)
{
if (board[i][0] == 'O')
dfs(i, 0, board);
if (board[i][col - 1] == 'O')
dfs(i, col - 1, board);
}
for (int j = 0;j<col;j++)
{
if (board[0][j] == 'O')
dfs(0, j, board);
if (board[row - 1][j] == 'O')
dfs(row - 1, j, board);
}
for (int i = 0;i<row;i++)
for (int j = 0;j<col;j++)
{
if (board[i][j] == 'O')
board[i][j] = 'X';
else if (board[i][j] == 'a')
board[i][j] = 'O';
}
}
void dfs(int i, int j, vector<vector<char>> &board)
{
int row = board.size();
int col = board[0].size();
board[i][j] = 'a';
for (int k = 0;k<4;k++)
{
int x = i + dir[k][0];
int y = j + dir[k][1];
if (x >= 0 && x<row&&y >= 0 && y<col)
if (board[x][y] == 'O')
dfs(x, y, board);
}
}
};
#leetcode##笔试题目#