-1

Question Link: LeetCode, I am getting runtime error but not found where it is causing. Why it is giving runtime error any one can explain it to me?

class Solution {
public:
    bool dfs(vector<vector<int>>& grid, int row, int col, int color)
    {
        if(row<0 || col<0 || row>=grid.size() || col>=grid[0].size() || abs(grid[row][col])!=color)
            return false;
        grid[row][col]=-color;
        bool first = dfs(grid, row-1, col, color);
        bool second = dfs(grid, row, col+1, color);
        bool third = dfs(grid, row+1, col, color);
        bool fourth = dfs(grid, row, col-1, color);
        if(first && second && third && fourth)
        {
            grid[row][col]=color;
        }
        return true;
    }
    vector<vector<int>> colorBorder(vector<vector<int>>& grid, int row, int col, int color) {
        
        dfs(grid, row, col, grid[row][col]);
        for(int i=0; i<grid.size(); i++)
        {
            for(int j=0; j<grid[0].size(); j++)
            {
                if(grid[i][j]<0)
                    grid[i][j]=color;
            }
        }
        return grid;    
    }
};
starball
  • 20,030
  • 7
  • 43
  • 238
  • 1
    Time to learn some things that such site won't teach you: First how to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your programs, and how to use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). Create a [mre] with hard-coded input, build and debug locally. – Some programmer dude May 16 '22 at 11:53
  • In `colorBorder`: shouldn't `j – wohlstad May 16 '22 at 11:54
  • 1
    Please include the error as well in your question. – Avinash May 16 '22 at 11:55
  • 4
    `dfs(0, 0)` will call `dfs(0, 1)`, which will call `dfs(0, 0)`, which will call `dfs(0, 1)`, which will call `dfs(0, 0)`, ... It never ends. – molbdnilo May 16 '22 at 11:58
  • @molbdnilo i got your point thanks for your explanation – Sunil Panchal May 19 '22 at 04:28

1 Answers1

2

I've wrote test for your code: https://godbolt.org/z/TazozK8xe and enabled address sanitizer.

Without reading your code and just by reading sanitizer logs you can see you have infinitive recursion (note number of stack frames is more then 178, when problem is simple to do it in maximum 4 steps). Basically your condition to stop recursion is wrong or incomplete.

I recommend you to learn how to use debugger so you can easier understand this issue.

Marek R
  • 32,568
  • 6
  • 55
  • 140