# What is wrong with my code? Runtime error

• ``````void solve(vector<vector<char>>& board) {
if(!board.size()) return ;

for(int i = 0; i < board.size(); i++)
{
for(int j = 0; j < board[0].size(); j++)
{
if((i == 0 || j == 0 || (i == board.size()-1) || (j == board[0].size()-1)) && (board[i][j] == 'O'))
{
dfs(board, i, j);
}
}
}

for(int i = 0; i < board.size(); i++)
{
for(int j = 0; j < board[0].size(); j++)
{
if(board[i][j] == 'O')
board[i][j] = 'X';
if(board[i][j] == '-')
board[i][j] = 'O';
}
}
}

void dfs(vector<vector<char>> & board, int row, int col)
{
board[row][col] = '-';
if((row >= 1) && (board[row-1][col] == 'O'))
dfs(board, row-1, col);
if((row < (board.size()-1)) && (board[row+1][col] == 'O'))
dfs(board, row+1, col);
if((col >= 1) && (board[row][col-1] == 'O'))
dfs(board, row, col-1);
if((col < (board[0].size()-1)) && (board[row][col+1] == 'O'))
dfs(board, row, col+1);
}
``````

First i use dfs to replace not surrounded 'O' with '-'.Then i replace '-' with 'O' and 'O' with 'X'.but i got a Runtime error message.

• Look at the test case you fail, don't be lazy :-P

You fail the test with a very long "O"-path, which probably causes a stack overflow due to the very deep recursion. You might have to write this non-recursively.

• thanks, i see

• @StefanPochmann Thanks,your post helps a lot!
I searched "runtime error" in this topic and get more than 10 threads, including recent ones, which do not get an satisfying answer. Your answer should be put on the very top!

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