# My code has runtime error and I do not understand why

• ``````class Solution {
public:
void solve(vector<vector<char>>& board) {
if(board.size()==0) return; /*always check for this*/
int rows=board.size(), cols=board[0].size();
for(int j=0; j<cols; ++j){
if(board[0][j]=='O'){
DFS(board, 0, j);
}
}
for(int i=0; i<rows; ++i){
if(board[i][0]=='O'){
DFS(board, i, 0);
}
}
for(int i=0; i<rows; ++i){
if(cols > 0 && board[i][cols-1]=='O'){
DFS(board, i, cols-1);
}
}
for(int j=0; j<cols; ++j){
if(rows >0 && board[rows-1][j]=='O'){
DFS(board, rows-1, j);
}
}

for(int i=0; i<rows; ++i)
for(int j=0; j<cols; ++j)
if(board[i][j]=='O')
board[i][j]='X';

for(int i=0; i<rows; ++i)
for(int j=0; j<cols; ++j)
if(board[i][j]=='#')
board[i][j]='O';
}
private:
void DFS(vector<vector<char>>& board, int i, int j){
int rows=board.size(), cols=board[0].size();
board[i][j]='#';
if(i > 0 && board[i-1][j]=='O')
DFS(board, i-1, j);
if(i<rows-1 && board[i+1][j]=='O')
DFS(board, i+1, j);
if(j>0 && board[i][j-1]=='O')
DFS(board, i, j-1);
if(j<cols-1 && board[i][j+1]=='O')
DFS(board, i, j+1);
}
};``````

• your code may causes a stack overflow issue, try BFS solutions

• Hi, I came across the same problem.
change the code

`if(i > 0 && board[i-1][j]=='O') DFS(board, i-1, j);`

to

`if(i > 1 && board[i-1][j]=='O') DFS(board, i-1, j);`

and use `j > 1` instead of`j > 0` in the next next if statement.

It was accepted but I do not understand why your solution causes runtime error.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.