# C++ program to find whether there is a path between two cells in matrix

In this article, we will be discussing a program to find whether there exists a path between two cells in a given matrix.

Let us suppose we have been given a square matrix with possible values 0, 1, 2 and 3. Here,

• 0 means Blank Wall
• 1 means Source
• 2 means Destination
• 3 means Blank Cell

There can only be one Source and Destination in the matrix. The program is to see if there’s a possible path from Source to Destination in the given matrix moving in all four possible directions but not diagonally.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
//creating a possible graph from given array
class use_graph {
int W;
public :
use_graph( int W ){
this->W = W;
}
void add_side( int source , int dest );
bool search ( int source , int dest);
};
void use_graph :: add_side ( int source , int dest ){
}
//function to perform BFS
bool use_graph :: search(int source, int dest) {
if (source == dest)
return true;
// initializing elements
bool *visited = new bool[W];
for (int i = 0; i < W; i++)
visited[i] = false;
list<int> queue;
//marking elements visited and removing them from queue
visited[source] = true;
queue.push_back(source);
list<int>::iterator i;
while (!queue.empty()){
source = queue.front();
queue.pop_front();
if (*i == dest)
return true;
if (!visited[*i]) {
visited[*i] = true;
queue.push_back(*i);
}
}
}
//if destination is not reached
return false;
}
bool is_okay(int i, int j, int M[][4]) {
if ((i < 0 || i >= 4) || (j < 0 || j >= 4 ) || M[i][j] == 0)
return false;
return true;
}
bool find(int M[][4]) {
int source , dest ;
int W = 4*4+2;
use_graph g(W);
int k = 1 ;
for (int i =0 ; i < 4 ; i++){
for (int j = 0 ; j < 4; j++){
if (M[i][j] != 0){
if ( is_okay ( i , j+1 , M ) )
g.add_side ( k , k+1 );
if ( is_okay ( i , j-1 , M ) )
g.add_side ( k , k-1 );
if (j < 4-1 && is_okay ( i+1 , j , M ) )
g.add_side ( k , k+4 );
if ( i > 0 && is_okay ( i-1 , j , M ) )
g.add_side ( k , k-4 );
}
if( M[i][j] == 1 )
source = k ;
if (M[i][j] == 2)
dest = k;
k++;
}
}
return g.search (source, dest) ;
}
int main(){
int M[4][4] = { { 0 , 3 , 0 , 1 }, { 3 , 0 , 3 , 3 }, { 2 , 3 , 0 , 3 },{ 0 , 0 , 3 , 0 }};
(find(M) == true) ?
cout << "Possible" : cout << "Not Possible" <<endl ;
return 0;
}

## Output

Not Possible

Updated on: 03-Oct-2019

113 Views