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

editclose

play_arrow

linkbrightness_4code

// C++ program to find path between two

// cell in matrix

#include<bits/stdc++.h>

usingnamespacestd;

#define N 4

classGraph

{

intV ;

list < int> *adj;

public:

Graph( intV )

{

this->V = V ;

adj = newlist<int>[V];

}

voidaddEdge( ints , intd ) ;

boolBFS ( ints , intd) ;

};

// add edge to graph

voidGraph :: addEdge ( ints , intd )

{

adj[s].push_back(d);

adj[d].push_back(s);

}

// BFS function to find path from source to sink

boolGraph :: BFS(ints, intd)

{

// Base case

if(s == d)

returntrue;

// Mark all the vertices as not visited

bool*visited = newbool[V];

for(inti = 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)

returntrue;

// Else, continue to do BFS

if(!visited[*i])

{

visited[*i] = true;

queue.push_back(*i);

}

}

}

// If BFS is complete without visiting d

returnfalse;

}

boolisSafe(inti, intj, intM[][N])

{

if((i < 0 || i >= N) ||

(j < 0 || j >= N ) || M[i][j] == 0)

returnfalse;

returntrue;

}

// Returns true if there is a path from a source (a

// cell with value 1) to a destination (a cell with

// value 2)

boolfindPath(intM[][N])

{

ints , d ; // source and destination

intV = N*N+2;

Graph g(V);

// create graph with n*n node

// each cell consider as node

intk = 1 ; // Number of current vertex

for(inti =0 ; i < N ; i++)

{

for(intj = 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

returng.BFS (s, d) ;

}

// driver program to check above function

intmain()

{

intM[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 ;

return0;

}

chevron_right

filter_none

Python3

filter_none

editclose

play_arrow

linkbrightness_4code

# Python3 program to find path between two

# cell in matrix

fromcollections importdefaultdict

classGraph:

def__init__(self):

self.graph =defaultdict(list)

# add edge to graph

defaddEdge(self, u, v):

self.graph[u].append(v)

# BFS function to find path from source to sink

defBFS(self, s, d):

# Base case

ifs ==d:

returnTrue

# 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

fori inself.graph[s]:

# If this adjacent node is the destination

# node, then return true

ifi ==d:

returnTrue

# Else, continue to do BFS

ifvisited[i] ==False:

queue.append(i)

visited[i] =True

# If BFS is complete without visiting d

returnFalse

defisSafe(i, j, matrix):

ifi >=0andi <=len(matrix) andj >=0andj <=len(matrix[0]):

returnTrue

else:

returnFalse

# Returns true if there is a path from a source (a

# cell with value 1) to a destination (a cell with

# value 2)

deffindPath(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

fori inrange(N):

forj inrange(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 -1andisSafe(i +1, j, M)):

g.addEdge(k, k +N)

if(i > 0andisSafe(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

returng.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]]

iffindPath(M):

print("Yes")

else:

print("No")

# This Code is Contributed by Vikash Kumar 37

chevron_right

filter_none

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.