Please help me. Why can't my c++ DFS code pass? I got runtime errror and found it leads to heap overflow.


  • 0
    L
    public:
    	void solve(vector<vector<char>>& grid)  {
    		if(grid.size() == 0)
    			return ;
    		int x = grid.size(), y = grid[0].size();
    
    		for (int i = 0; i < x; ++i)
    		{
    			for(int j = 0; j < y; ++j){
    				if((i == 0 || j == 0 || i == x-1  || j == y-1) && (grid[i][j] == 'O'))
    					internalSolveDFS( grid, i,j, x, y);
    			}
    		}
    	
    		for (int i = 0; i < x; ++i)
    		{
    			for(int j = 0; j < y; ++j){
    				if(grid[i][j] == 'O')
    					grid[i][j] = 'X';
    				else if(grid[i][j] == '-')
    					grid[i][j] = 'O';
    			}
    		}
    	}
    private:
    	void internalSolveDFS(vector<vector<char>>& grid, int i, int j, int row, int col){   
    		if(i >= row || j >= col || i < 0 || j <0)
    			return;
    
    
    		 if (grid[i][j] == 'O') {
    			grid[i][j] = '-';
    
    			internalSolveDFS(grid, i-1, j,row, col);
    			internalSolveDFS(grid, i+1, j,row, col);
    			internalSolveDFS(grid, i, j-1,row, col);
    			internalSolveDFS(grid, i, j+1,row, col);
    		}
    	}

Log in to reply
 

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