Find whether path exist | Practice | GeeksforGeeks

Given a grid of size n*n filled with 0, 1, 2, 3. Check whether there is a path possible from the source to destination. You can traverse up, down, right and left.
The description of cells is as follows:
A value of cell 1 means Source.
A value of cell 2 means Destination.
A value of cell 3 means Blank cell.
A value of cell 0 means Wall.
Note: There are only a single source and a single destination.
 
Example 1:
Input: grid = {{3,0,3,0,0},{3,0,0,0,3}
,{3,3,3,3,3},{0,2,3,0,0},{3,0,0,1,3}}
Output: 0
Explanation: The grid is-
3 0 3 0 0 
3 0 0 0 3 
3 3 3 3 3 
0 2 3 0 0 
3 0 0 1 3 
There is no path to reach at (3,1) i,e at 
destination from (4,3) i,e source.

Example 2:
Input: grid = {{1,3},{3,2}}
Output: 1
Explanation: The grid is-
1 3
3 2
There is a path from (0,0) i,e source to (1,1) 
i,e destination.

 
Your Task:
You don't need to read or print anything. Your task is to complete the function is_Possible() which takes the grid as input parameter and returns boolean value true if there is a path otherwise returns false.
 
Expected Time Complexity: O(n2)
Expected Auxiliary Space: O(n2)
 
Constraints:
1 ≤ n ≤ 500
0
21mx1262 days ago
No extra space and O(n^2) Time Complexity Time take (0.01)/(2.5)
 
void solve(vector<vector<int>>& grid,int i,int j,bool& set,int r,int c){              if(set)return;              if(i<0||i>=r||j<0||j>=c||grid[i][j]==0){           return;       }              if(grid[i][j]==2){set=true;return;}              grid[i][j]=0;              solve(grid,i-1,j,set,r,c);       solve(grid,i,j+1,set,r,c);       solve(grid,i+1,j,set,r,c);       solve(grid,i,j-1,set,r,c);          }      bool is_Possible(vector<vector<int>>& grid)    {       //code here       bool set=false;       int r = grid.size(),c = grid[0].size();              for(int i=0;i<r;i++){           for(int j=0;j<c;j++){               if(grid[i][j]==1){                   solve(grid,i,j,set,r,c);               }           }       }              return set;          }
0
yash_raj_singh2 weeks ago
SIMPLE AND EASY USING BFS IN CPP (0.01 TIME)

class Solution
{
    public:
    //Function to find whether a path exists from the source to destination.
    
    int dx[4] = {0 ,0 , 1, -1};
    int dy[4] = {1, -1, 0 , 0};
    
    bool isValid(int a, int b, int n)
    {
        if(a<0 || b<0 || a>=n || b>=n)
        {
            return false;
        }
        
        return true;
    }
    
    bool is_Possible(vector<vector<int>>& grid) 
    {
        int n = grid.size();
        
        queue<vector<int>> q;
        
        vector<int> s;
        vector<int> d;
        
        for(int i=0; i<n; i++)
        {
            for(int j = 0;j<n; j++)
            {
                if(grid[i][j] == 1)
                {
                    s.emplace_back(i);
                    
                    s.emplace_back(j);
                }
                
                if(grid[i][j] == 2)
                {
                    d.emplace_back(i);
                    
                    d.emplace_back(j);
                }
            }
        }
        
        
        q.push({s[0],s[1]});
        
        while(!q.empty())
        {
            auto a = q.front();
            q.pop();
            
            for(int x = 0; x<4; x++)
            {
                int t = a[0] + dx[x];
                int y = a[1] + dy[x];
                
                if(t == d[0] && y == d[1])
                {
                    return true;
                }
                
                if(isValid(t, y, n) && grid[t][y] == 3)
                {
                    grid[t][y] = 5;
                    q.push({t,y});
                }
            }
        }
        
        return false;
    }
};

0
insanelion2 weeks ago
class Solution
{
    //Function to find whether a path exists from the source to destination.
    public boolean is_Possible(int[][] grid)
    {
        // Code here
        boolean visited[][] = new boolean[grid.length][grid[0].length];
        for(int i=0;i<grid.length;i++) {
            for(int j=0;j<grid[i].length;j++) {
                if(grid[i][j]==1)
                return hasPath(grid,visited,i,j);
            }
        }
        return false;
    }
    public boolean hasPath(int grid[][],boolean visited[][],int x,int y) {
        if(grid[x][y]==2)
        return true;
        
        visited[x][y] = true;
        boolean test = false;
        if(x>0&&grid[x-1][y]!=0&&!visited[x-1][y]) 
        test = test || hasPath(grid,visited,x-1,y);//right
        if(y>0&&grid[x][y-1]!=0&&!visited[x][y-1])
        test = test || hasPath(grid,visited,x,y-1);//down
        if(x<grid.length-1&&grid[x+1][y]!=0&&!visited[x+1][y])
        test = test || hasPath(grid,visited,x+1,y);//;left
        if(y<grid.length-1&&grid[x][y+1]!=0&&!visited[x][y+1])
        test = test || hasPath(grid,visited,x,y+1);//up
        visited[x][y] = false;
        return test;
        
        
    }
}
0
19bcs13143 weeks ago
class Pair{
    int i,j;
    Pair(int i,int j){
        this.i=i;
        this.j=j;
    }
}
class Solution
{
    int n=0;
    //Function to find whether a path exists from the source to destination.
    public boolean is_Possible(int[][] g)
    {
        // Code here
        this.n=g.length;
        boolean[][] visit=new boolean[n][n];
       for(int i=0;i<n;i++){
           for(int j=0;j<n;j++){
               if(g[i][j]==1){
                   return bfs(g,i,j,visit);
               }
           }
       }
       return false;
        
    }
    public boolean isValid(int[][] g,int x,int y,int n,boolean[][] visit){
        if(x<0 || x>=n || y<0 || y>=n || visit[x][y]==true || g[x][y]==0){
            return false;
        }
        return true;
    }
    
    int[] dx={0,0,-1,1};
    int[] dy={-1,1,0,0};
    public boolean bfs(int[][] g,int u,int v,boolean[][] visit){
         Queue<Pair> q=new ArrayDeque<>();
         visit[u][v]=true;
         q.add(new Pair(u,v));
         while(q.size()!=0){
             Pair temp=q.remove();
             int x=temp.i,y=temp.j;
             
             if(g[x][y]==2){
                 return true;
             }
             else{
                 
                 for(int k=0;k<4;k++){
                     
                     if(isValid(g,x+dx[k],y+dy[k],n,visit)){
                         q.add(new Pair(x+dx[k],y+dy[k]));
                         visit[x+dx[k]][y+dy[k]]=true;
                     }
                 }
             }
         }
         
         return false;
    }
}
0
hamidnourashraf4 weeks ago
class Solution:
    
    def rec_traverse(self, grid, i, j, n, mem, visited):
        if i < 0 or i >= n or j < 0 or j >= n:
            return False
        if grid[i][j] == 2:
            mem[i][j] = True
            return mem[i][j]
        if grid[i][j] == 0:
            mem[i][j] = False
            return mem[i][j]
        if mem[i][j] != -1:
            return mem[i][j]
        if visited[i][j] == 0:
            return False
        visited[i][j] = 0
        up = self.rec_traverse(grid, i-1, j, n, mem, visited)    
        down = self.rec_traverse(grid, i+1, j, n, mem, visited)
        right = self.rec_traverse(grid, i, j+1, n, mem, visited)    
        left = self.rec_traverse(grid, i, j-1, n, mem, visited)
        mem[i][j] = (up or down or right or left)
        visited[i][j] = -1
        return mem[i][j]
        
    def is_Possible(self, grid):
        n = len(grid)
        mem = [[-1]*n for i in range(n)]
        visited = [[-1]*n for i in range(n)]
        for i in range(n):
            for j in range(n):
                if grid[i][j] == 1:
                    return self.rec_traverse(grid, i, j, n, mem, visited)
0
phenomenal11 month ago
JAVA BACKTRACKING SOLUTION:
class Solution{   boolean flag=false;      public boolean is_Possible(int[][] grid)   {       int start_i=-1,start_j=-1;       boolean flag2=false;       boolean vis[][] = new boolean[grid.length][grid.length];       for(int i=0;i<grid.length;i++)       {           for(int j=0;j<grid[0].length;j++)           {               if(grid[i][j]==1)               {                   start_i=i;                   start_j=j;                   flag2=true;                   break;               }           }       }       if(!flag2)       return false;              path(grid,start_i,start_j,vis);              return flag;   }      void path(int [][] grid,int i,int j,boolean vis[][])   {       if(grid[i][j] == 2)       {          // System.out.print(grid[i][j]+" ");           flag = true;           return;       }              //UP       if((i-1)>=0 && grid[i-1][j]!=0 && !vis[i-1][j])       {           vis[i][j]=true;           //System.out.print(grid[i][j]+" ");           path(grid,i-1,j,vis);           vis[i][j]=false;       }              //DOWN       if((i+1)<grid.length && grid[i+1][j]!=0 && !vis[i+1][j])       {           vis[i][j]=true;          // System.out.print(grid[i][j]+" ");           path(grid,i+1,j,vis);           vis[i][j]=false;       }              //LEFT       if((j-1)>=0 && grid[i][j-1]!=0 && !vis[i][j-1])       {           vis[i][j]=true;           //System.out.print(grid[i][j]+" ");           path(grid,i,j-1,vis);           vis[i][j]=false;       }              //RIGHT       if((j+1)<grid.length && grid[i][j+1]!=0 && !vis[i][j+1])       {           vis[i][j]=true;          // System.out.print(grid[i][j]+" ");           path(grid,i,j+1,vis);           vis[i][j]=false;       }   }}
0
bhaskarmaheshwari81 month ago
 bool isSafe(  vector<vector<int>> &grid,  vector<vector<int>> &vis,int row,int col)   {       int n=grid.size();       if(row<0||col<0||row>n-1||col>n-1||vis[row][col]||grid[row][col]==0)       return 0;       return 1;   }   bool dfs(vector<vector<int>>& grid,  vector<vector<int>> &vis,int row,int col)   {       if(grid[row][col]==2)       {           return 1;       }       vis[row][col]=1;       int dx[]={-1,1,0,0};       int dy[]={0,0,-1,1};              for(int i=0;i<4;i++)       {           // for(int j=0;j<4;j++)           // {             // }                       if(isSafe(grid,vis,row+dx[i],col+dy[i]))              if(dfs(grid,vis,row+dx[i],col+dy[i]))              return 1;       }       return 0;   }   bool is_Possible(vector<vector<int>>& grid)    {       //code here       int n=grid.size();              vector<vector<int>> vis(n+1,vector<int>(n+1,0));              for(int i=0;i<n;i++)       {           for(int j=0;j<n;j++)           {               if(grid[i][j]==1)               {                  return dfs(grid,vis,i,j);                                }           }       }          }
0
lindan1231 month ago
bool solve(vector<vector<int>>& grid,vector<vector<int>>& visit,int n, int m,int i, int j)
    {
        if(i>=n || i<0 || j>=m || j<0 || visit[i][j]!=0 || grid[i][j]==0)
        {
            return false;
        }
        if(grid[i][j]==2)
        {
            return true;
        }
        
        visit[i][j] = 1;
        
        bool a = solve(grid,visit,n,m,i-1,j);
        bool b = solve(grid,visit,n,m,i+1,j);
        bool c = solve(grid,visit,n,m,i,j-1);
        bool d = solve(grid,visit,n,m,i,j+1);
        return a || b || c || d;
    }
    bool is_Possible(vector<vector<int>>& grid) 
    {
        
        int n = grid.size();
        int m = grid[0].size();
        vector<vector<int> > visit(n,vector<int>(m,0));
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(grid[i][j]==1)
                {
                    return solve(grid,visit,n,m,i,j);
                }
            }
        }
        return false;
    }
Time Taken : 0.0sec
Cpp
+1
himanshukug19cs2 months ago
java solution
 
class pair{       int x;       int y;       pair(int x,int y){           this.x=x;           this.y=y;       }   }   boolean[][] vis;   boolean isValid(pair np,int n,int m,int[][] grid){       if(np.x<0||np.y<0||np.x>=n||np.y>=m||grid[np.x][np.y]==0||vis[np.x][np.y]==true)           return false;       return true;     }   boolean sol(pair src,pair des,int[][] grid){       ArrayDeque<pair> dq = new ArrayDeque<>();       int[] xarr={-1,0,1,0};       int[] yarr={0,1,0,-1};       dq.add(src);       while(!dq.isEmpty()){           pair re=dq.remove();           if(grid[re.x][re.y]==2)               return true;           vis[re.x][re.y]=true;           for(int i=0;i<4;i++){               pair np= new pair(re.x+xarr[i],re.y+yarr[i]);               if(isValid(np,grid.length,grid[0].length,grid))                   dq.add(np);           }       }       return false;   }   public boolean is_Possible(int[][] grid)   {       // Code here       vis= new boolean[grid.length][grid[0].length];       pair src= new pair(-1,-1);       pair des= new pair(-1,-1);       for(int i=0;i<grid.length;i++){           for(int j=0;j<grid[0].length;j++){               if(grid[i][j]==1){                   src.x=i;                   src.y=j;               }               if(grid[i][j]==2){                   des.x=i;                   des.y=j;               }           }       }       if(src.x==-1||src.y==-1||des.x==-1||des.y==-1)          return false;       return sol(src,des,grid);   }
+1
madhukartemba2 months ago
JAVA SOLUTION USING BFS:
class Pair
{
    int x, y;
    
    Pair(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

class Solution
{
    private boolean inLimits(int x, int y, int n)
    {
        return (x>=0 && y>=0 && x<n && y<n);
    }
    
    //Function to find whether a path exists from the source to destination.
    public boolean is_Possible(int[][] grid)
    {
        Pair src= null, dest;
        int n = grid.length;
        Queue<Pair> queue = new ArrayDeque<>();
        
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<n; j++)
            {
                if(grid[i][j]==1)
                {
                    src = new Pair(i, j);
                    break;
                }
            }
        }
        
        queue.offer(src);
        
        int dx[] = {1, 0, -1, 0};
        int dy[] = {0, 1, 0, -1};
        
        while(queue.isEmpty()==false)
        {
            Pair p = queue.poll();
            
            grid[p.x][p.y] = -1;
            
            for(int i=0; i<4; i++)
            {
                int x = p.x + dx[i];
                int y = p.y + dy[i];
                
                if(inLimits(x, y, n) && grid[x][y] > 1)
                {
                    if(grid[x][y] == 2) return true;
                    
                    queue.add(new Pair(x, y));
                    
                }
            }
        }
        
        
        return false;
        
    }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.