Help!!! Why when I use run code the outcome matches the answer, but when I submit,it has a Runtime Error?


  • 0
    Y

    class Solution {
    public:
    void solve(vector<vector<char>>& board) {
    if(board.size()==0)
    return;
    int row = board.size();
    int col = board[0].size();

        for(int i=0;i<row;i++)
            {
                if(board[i][0]=='O')
                    helper(i,0,board);
                if(board[i][col-1]=='O')
                    helper(i,col-1,board);
            }
            
         for(int i=0;i<col;i++)
            {
                if(board[0][i]=='O')
                    helper(0,i,board);
                if(board[row-1][i]=='O')
                    helper(row-1,i,board);
            }
    
        for(int i=0;i<row;i++)
            for(int j=0;j<col;j++)
                {
                    if(board[i][j]=='#')
                        board[i][j] = 'O';
                    else
                        board[i][j] = 'X';
                }
                
    }
    void helper(int i,int j,vector<vector<char> >&board)
    {
        if(i<0||i>=board.size()||j<0||j>=board[0].size()||board[i][j]!='O')
            return;
        board[i][j] = '#';
       // if(i>1&&board[i-1][j]=='O')
        helper(i-1,j,board);
        //if(i<board.size()-1&&board[i+1][j]=='O')
        helper(i+1,j,board);
        //if(j>1&&board[i][j-1]=='O')
        helper(i,j-1,board);
        //if(j<board[0].size()-1&&board[i][j+1]=='O')
        helper(i,j+1,board);
    }
    

    };


  • 0
    E

    Same situation with me, and I am still can't figure it out.
    The official explanation to this phenomenon is at https://leetcode.com/faq/#different-output.


  • 0
    G

    This is most likely a stack overflow with a very large input. Your helper function has a tail recursion, it is very easy to convert to an iterative method that will use the heap instead of the stack. Try using a queue ...


Log in to reply
 

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