Got runtime error. Can someone help?

  • 0

    The idea of my approach is to start from the boundary, if the we see an 'O', we mark it as 'K', then we look at all of its four neighbors. If we see an 'O', we continue. Instead of using a bool matrix to keep the visited nodes, I use the board its self with the marks 'K'. At the end, change all 'K' to 'O', and everything else to 'X'.
    Unfortunately, I got a run time error when the size is 250*250. Can someone help me to find the errors?
    Thank you!

    class Solution {
        void solve(vector<vector<char>> &board) {
            int n = board.size();
            int m = board[0].size();
            for(int i=0; i<n; i++)
                for(int j=0; j<m; j++)
                    if((i==0 || j==0 || i==n-1 || j==m-1) && board[i][j] == 'O')  // only from the boundary
                        change(board, i, j, n, m);
            for(int i=0; i<n ; i++)
                for(int j=0; j<m; j++)
                    if(board[i][j] == 'K')
                        board[i][j] = 'O';
                        board[i][j] = 'X';
        void change(vector<vector<char>> &board, int i, int j, int n, int m){
            board[i][j] = 'K';
            if(i-1>=0 && board[i-1][j] == 'O')
                change(board, i-1, j, n, m);
            if(i+1<n && board[i+1][j] == 'O')
                change(board, i+1, j, n, m);
            if(j-1>=0 && board[i][j-1] == 'O')
                change(board, i, j-1, n, m);
            if(j+1<m && board[i][j+1] == 'O')
                change(board, i, j+1, n, m);

  • 0

    It is highly possible that the runtime error is caused by exceeding maximum recursion depth, i.e. running out of stack memory.

Log in to reply

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