Home > Software engineering >  hey im getting segmentation fault in below code for rat in a maze problem
hey im getting segmentation fault in below code for rat in a maze problem

Time:07-25

the standard rat in maze problem is given a binary grid if grid[i][j]==0 path blocked rat is in 0,0 find all ways to reach n-1,n-1 cell. I have put all the constraints I guess.

  class Solution{
    public:
    // vector<string>ans;
    // vector<pair<int,int>>dir={{0,1},{0,-1},{-1,0},{1,0}};
    // vector<string>move={"R","L","U","D"};
    void dfs(int i,int j,vector<vector<int>>&m,string 
    curr,vector<vector<int>>&visited,vector<pair<int,int>>dir,vector<string>move,vector<string>&ans){
            if(i==m.size()-1 and j==m.size()-1){
                ans.push_back(curr);
                return;
            }


    for(int z=0;z<dir.size();z   ){
        int nx=i dir[z].first;
        int ny=j dir[z].second;
        if(visited[nx][ny]==0 and m[nx][ny]==1 and nx>=0 and nx<m.size() and ny>=0 and 
        ny<m.size() ){
             visited[nx][ny]=1;
             dfs(nx,ny,m,curr move[z],visited,dir,move,ans);
             visited[nx][ny]=0;
        }    
    }
    
}
vector<string> findPath(vector<vector<int>> &m, int n) {
 vector<vector<int>>visited(m.size(),vector<int>(n,0));
 string curr="";
 vector<string>ans;
 vector<pair<int,int>>dir={{0,1},{0,-1},{-1,0},{1,0}};
 vector<string>move={"R","L","U","D"};
 dfs(0,0,m,curr,visited,dir,move,ans);
 return ans;   
}

};

CodePudding user response:

Change

if (visited[nx][ny]==0 and m[nx][ny]==1 and 
    nx>=0 and nx<m.size() and ny>=0 and ny<m.size()) {

to

if (nx>=0 and nx<m.size() and ny>=0 and ny<m.size() and 
    visited[nx][ny]==0 and m[nx][ny]==1) {

You should only check visited and m after you have checked that nx and ny are in bounds. The order of the two sides of an and expression matters.

CodePudding user response:

visited[nx][ny] == 0 is out-of-bounds. m[nx][ny] == 1 is out-of-bounds too.

  • Related