Find whether there is path between two cells in matrix

Given N X N matrix filled with 1 , 0 , 2 , 3 . Find whether there is a path possible from source to destination, traversing through blank cells only. You can traverse up, down, right and left.

  • 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 Blank Wall.

Note : there is only single source and single destination(sink).

Examples:



Input : M[3][3] = {{ 0 , 3 , 2 },
                   { 3 , 3 , 0 },
                   { 1 , 3 , 0 }};
Output : Yes

Input : M[4][4] = {{ 0 , 3 , 1 , 0 },
                   { 3 , 0 , 3 , 3 },
                   { 2 , 3 , 0 , 3 },
                   { 0 , 3 , 3 , 3 }};
Output : Yes

Asked in: Adobe Interview

Simple solution is that find the source index of cell in matrix and then recursively find a path from source index to destination in matrix .
algorithm :

Find source index in matrix , let we consider ( i , j )
After that Find path from source(1) to sink(2)
FindPathUtil ( M[][N] , i  , j )

   IF we seen M[i][j] == 0 (wall) ||
      ((i, j) is out of matrix index)
     return false ;
   IF we seen destination M[i][j] == 2
     return true ;
   
   Next move in path by traverse all 4 adjacent  
   cell of current cell
   IF (FindPathUtil(M[][N], i+1, j) ||
       FindPathUtil(M[][N], i-1, j) ||
       FindPathUtil(M[][N], i, j+1) ||
       FindPathUtil(M[][N], i, j-1));
      return true ;

 return false ;

Below is the implementation of above approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find path between two 
// cell in matrix 
class Path {
      
    // method for finding and printing 
    // whether the path exists or not
    public static void isPath(int matrix[][], int n)
    {
        // defining visited array to keep 
        // track of already visited indexes
        boolean visited[][] = new boolean[n][n];
          
        // flag to indicate whether the path exists or not
        boolean flag=false;
          
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                // if matrix[i][j] is source 
                // and it is not visited
                if(matrix[i][j]==1 && !visited[i][j])
                  
                // starting from i, j and then finding the path
                if(isPath(matrix, i, j, visited))
                {
                        flag=true; // if path exists
                        break;
                }
            }
        }
        if(flag)
            System.out.println("YES");
        else
        System.out.println("NO");
    }
      
      
    // method for checking boundries
    public static boolean isSafe(int i, int j, int matrix[][])
    {
          
        if(i>=0 && i<matrix.length && j>=0 
                       && j<matrix[0].length)
            return true;
        return false
    }
      
    // Returns true if there is a path from a source (a 
    // cell with value 1) to a destination (a cell with 
    // value 2) 
    public static boolean isPath(int matrix[][], 
                    int i, int j, boolean visited[][]){
          
        // checking the boundries, walls and 
        // whether the cell is unvisited
        if(isSafe(i, j, matrix) && matrix[i][j]!=0 
                                    && !visited[i][j])
        {
            // make the cell visited
            visited[i][j]=true;
              
            // if the cell is the required 
            // destination then return true
            if(matrix[i][j]==2)
                return true;
              
            // traverse up
            boolean up = isPath(matrix, i-1, j, visited);
              
            // if path is found in up direction return true
            if(up)
                return true;
                  
            // traverse left
            boolean left = isPath(matrix, i, j-1, visited);
              
            // if path is found in left direction return true
            if(left)
                return true
                  
            //traverse down
            boolean down = isPath(matrix, i+1, j, visited);
              
            // if path is found in down direction return true
            if(down)
                return true;
                  
            // traverse right
            boolean right = isPath(matrix, i, j+1, visited);
              
            // if path is found in right direction return true
            if(right)
                return true;
        
        return false; // no path has been found 
    
      
    // driver program to check above function
      
    public static void main (String[] args) {
      
    int matrix[][] = {{0, 3, 0, 1},
                        {3, 0, 3, 3},
                        {2, 3, 3, 3},
                        {0, 3, 3, 3}};
                          
    isPath(matrix, 4);                 // calling isPath method 
    }
}
  
/* This code is contributed by Madhu Priya */

chevron_right


Efficient solution (Graph)
The idea is to use Breadth First Search. Consider each cell as a node and each boundary between any two adjacent cells be an edge. so total number of Node is N*N.

 1. Create an empty Graph having N*N node ( Vertex ).
 2. push all  node into graph.
 3. notedown source and sink vertex
 4. Now Appling BFS to find is there is path between
    to vertex or not in  graph
        IF Path found return true
        Else return False

below are the implementations of above idea.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find path between two
// cell in matrix
#include<bits/stdc++.h>
using namespace std;
#define N 4
  
class Graph
{
    int V ;
    list < int > *adj;
public :
    Graph( int V )
    {
        this->V = V ;
        adj = new list<int>[V];
    }
    void addEdge( int s , int d ) ;
    bool BFS ( int s , int d) ;
};
  
// add edge to graph
void Graph :: addEdge ( int s , int d )
{
    adj[s].push_back(d);
    adj[d].push_back(s);
}
  
// BFS function to find path from source to sink
bool Graph :: BFS(int s, int d)
{
    // Base case
    if (s == d)
        return true;
  
    // Mark all the vertices as not visited
    bool *visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;
  
    // Create a queue for BFS
    list<int> queue;
  
    // Mark the current node as visited and
    // enqueue it
    visited[s] = true;
    queue.push_back(s);
  
    // it will be used to get all adjacent
    // vertices of a vertex
    list<int>::iterator i;
  
    while (!queue.empty())
    {
        // Dequeue a vertex from queue
        s = queue.front();
        queue.pop_front();
  
        // Get all adjacent vertices of the
        // dequeued vertex s. If a adjacent has
        // not been visited, then mark it visited
        // and enqueue it
        for (i = adj[s].begin(); i != adj[s].end(); ++i)
        {
            // If this adjacent node is the destination
            // node, then return true
            if (*i == d)
                return true;
  
            // Else, continue to do BFS
            if (!visited[*i])
            {
                visited[*i] = true;
                queue.push_back(*i);
            }
        }
    }
  
    // If BFS is complete without visiting d
    return false;
}
  
bool isSafe(int i, int j, int M[][N])
{
    if ((i < 0 || i >= N) ||
        (j < 0 || j >= N ) || M[i][j] == 0)
        return false;
    return true;
}
  
// Returns true if there is a path from a source (a
// cell with value 1) to a destination (a cell with
// value 2)
bool findPath(int M[][N])
{
    int s , d ; // source and destination
    int V = N*N+2;
    Graph g(V);
  
    // create graph with n*n node
    // each cell consider as node
    int k = 1 ; // Number of current vertex
    for (int i =0 ; i < N ; i++)
    {
        for (int j = 0 ; j < N; j++)
        {
            if (M[i][j] != 0)
            {
                // connect all 4 adjacent cell to
                // current cell
                if ( isSafe ( i , j+1 , M ) )
                    g.addEdge ( k , k+1 );
                if ( isSafe ( i , j-1 , M ) )
                    g.addEdge ( k , k-1 );
                if (j< N-1 && isSafe ( i+1 , j , M ) )
                    g.addEdge ( k , k+N );
                if ( i > 0 && isSafe ( i-1 , j , M ) )
                    g.addEdge ( k , k-N );
            }
  
            // source index
            if( M[i][j] == 1 )
                s = k ;
  
            // destination index
            if (M[i][j] == 2)
                d = k;
            k++;
        }
    }
  
    // find path Using BFS
    return g.BFS (s, d) ;
}
  
// driver program to check above function
int main()
{
    int  M[N][N] =    {{ 0 , 3 , 0 , 1 },
        { 3 , 0 , 3 , 3 },
        { 2 , 3 , 3 , 3 },
        { 0 , 3 , 3 , 3 }
    };
  
    (findPath(M) == true) ?
     cout << "Yes" : cout << "No" <<endl ;
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find path between two 
# cell in matrix 
from collections import defaultdict
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
      
    # add edge to graph
    def addEdge(self, u, v):
        self.graph[u].append(v)
  
    # BFS function to find path from source to sink     
    def BFS(self, s, d):
          
        # Base case
        if s == d:
            return True
              
        # Mark all the vertices as not visited 
        visited = [False]*(len(self.graph) + 1)
  
        # Create a queue for BFS 
        queue = []
        queue.append(s)
  
        # Mark the current node as visited and 
        # enqueue it 
        visited[s] = True
        while(queue):
  
            # Dequeue a vertex from queue
            s = queue.pop(0)
  
            # Get all adjacent vertices of the 
            # dequeued vertex s. If a adjacent has 
            # not been visited, then mark it visited 
            # and enqueue it 
            for i in self.graph[s]:
                  
                # If this adjacent node is the destination 
                # node, then return true 
                if i == d:
                    return True
  
                # Else, continue to do BFS 
                if visited[i] == False:
                    queue.append(i)
                    visited[i] = True
  
        # If BFS is complete without visiting d
        return False
  
def isSafe(i, j, matrix):
    if i >= 0 and i <= len(matrix) and j >= 0 and j <= len(matrix[0]):
        return True
    else:
        return False
  
# Returns true if there is a path from a source (a 
# cell with value 1) to a destination (a cell with 
# value 2)
def findPath(M):
    s, d = None, None # source and destination 
    N = len(M)
    g = Graph()
  
    # create graph with n*n node 
    # each cell consider as node 
    k = 1 # Number of current vertex
    for i in range(N):
        for j in range(N):
            if (M[i][j] != 0):
  
                # connect all 4 adjacent cell to 
                # current cell 
                if (isSafe(i, j + 1, M)):
                    g.addEdge(k, k + 1)
                if (isSafe(i, j - 1, M)):
                    g.addEdge(k, k - 1)
                if (j < N - 1 and isSafe(i + 1, j, M)):
                    g.addEdge(k, k + N)
                if (i > 0 and isSafe(i - 1, j, M)):
                    g.addEdge(k, k - N)
              
            if (M[i][j] == 1):
                s = k
  
            # destination index     
            if (M[i][j] == 2):
                d = k
            k += 1
  
    # find path Using BFS 
    return g.BFS(s, d)
  
# Driver code 
if __name__=='__main__':
    M=[[0,3,0,1],[3,0,3,3],[2,3,3,3],[0,3,3,3]]
    if findPath(M):
        print("Yes")
    else:
        print("No")
  
# This Code is Contributed by Vikash Kumar 37

chevron_right



Output:

 Yes

This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up