Find whether there is path between two cells in matrix
Last Updated : 10 Jun, 2026
Given a grid mat[][] of size n × n containing integers 0, 1, 2, and 3, determine whether a path exists from the source cell to the destination cell. Movement is allowed in four directions: up, down, left, and right.
1 represents the source cell
2 represents the destination cell
3 represents a blank cell through which movement is allowed
0 represents a wall that cannot be traversed
There is exactly one source and one destination in the grid.
Examples:
Input: mat[][] = {{0,3,1,0}, {3,0,3,3}, {2,3,0,3}, {0,3,3,3}}; Output: true Explanation: A path exists from source 1 to destination 2 through valid cells 3.
Input: mat[][] = {{1,0,3}, {0,0,0}, {3,3,2}}; Output: false Explanation: No path exists as the source 1 is blocked and cannot reach destination 2.
[Naive Approach] DFS / Backtracking – O(n^2 × 4^(n^2)) Time and O(n^2) Space
The idea is to first locate the source cell in the matrix and then use Depth First Search (DFS) with recursion to explore all possible paths from the source to the destination. From each cell, we try moving in all four directions (up, down, left, right) while ensuring we only visit valid and unvisited cells. The traversal continues recursively until the destination cell is found or all possible paths are exhausted.
Find the source cell (value 1) in the matrix.
Use DFS (recursion) starting from the source.
Mark the current cell as visited.
If the destination (2) is found, return true.
Explore all 4 directions (up, down, left, right).
Continue only on valid and unvisited cells.
If any path reaches the destination, return true; otherwise return false.
C++
usingnamespacestd;// Function to check whether a cell is within matrix boundsboolisSafe(intx,inty,intn){return(x>=0&&x<n&&y>=0&&y<n);}// DFS function to explore all possible pathsbooldfs(vector<vector<int>>&mat,intx,inty,vector<vector<bool>>&visited){intn=mat.size();// If out of bounds, or wall, or already visited → invalid pathif(!isSafe(x,y,n)||mat[x][y]==0||visited[x][y])returnfalse;// If destination cell is found → return trueif(mat[x][y]==2)returntrue;// Mark current cell as visitedvisited[x][y]=true;// Explore all 4 directions (up, down, left, right)boolup=dfs(mat,x-1,y,visited);booldown=dfs(mat,x+1,y,visited);boolleft=dfs(mat,x,y-1,visited);boolright=dfs(mat,x,y+1,visited);// If any direction leads to destination → return truereturnup||down||left||right;}boolisPathPossible(vector<vector<int>>&mat){intn=mat.size();// Visited array to avoid revisiting same cellvector<vector<bool>>visited(n,vector<bool>(n,false));// Find the source cell (value = 1)for(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i][j]==1){returndfs(mat,i,j,visited);}}}returnfalse;}intmain(){vector<vector<int>>mat={{0,3,1,0},{3,0,3,3},{2,3,0,3},{0,3,3,3}};// Check if path existsboolans=isPathPossible(mat);cout<<(ans?"true":"false")<<endl;return0;}
Java
classGFG{// Function to check whether a cell is within matrix boundsstaticbooleanisSafe(intx,inty,intn){return(x>=0&&x<n&&y>=0&&y<n);}// DFS function to explore all possible pathsstaticbooleandfs(int[][]mat,intx,inty,boolean[][]visited){intn=mat.length;// If out of bounds, or wall, or already visited → invalid pathif(!isSafe(x,y,n)||mat[x][y]==0||visited[x][y])returnfalse;// If destination cell is found → return trueif(mat[x][y]==2)returntrue;// Mark current cell as visitedvisited[x][y]=true;// Explore all 4 directions (up, down, left, right)booleanup=dfs(mat,x-1,y,visited);booleandown=dfs(mat,x+1,y,visited);booleanleft=dfs(mat,x,y-1,visited);booleanright=dfs(mat,x,y+1,visited);// If any direction leads to destination → return truereturnup||down||left||right;}staticbooleanisPathPossible(int[][]mat){intn=mat.length;// Visited array to avoid revisiting same cellboolean[][]visited=newboolean[n][n];// Find the source cell (value = 1)for(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i][j]==1){returndfs(mat,i,j,visited);}}}returnfalse;}publicstaticvoidmain(String[]args){int[][]mat={{0,3,1,0},{3,0,3,3},{2,3,0,3},{0,3,3,3}};// Check if path existsbooleanres=isPathPossible(mat);System.out.println(res);}}
Python
# Function to check whether a cell is within matrix boundsdefisSafe(x,y,n):return(x>=0andx<nandy>=0andy<n)# DFS function to explore all possible pathsdefdfs(mat,x,y,visited):n=len(mat)# If out of bounds, or wall, or already visited → invalid pathifnotisSafe(x,y,n)ormat[x][y]==0orvisited[x][y]:returnFalse# If destination cell is found → return trueifmat[x][y]==2:returnTrue# Mark current cell as visitedvisited[x][y]=True# Explore all 4 directions (up, down, left, right)up=dfs(mat,x-1,y,visited)down=dfs(mat,x+1,y,visited)left=dfs(mat,x,y-1,visited)right=dfs(mat,x,y+1,visited)# If any direction leads to destination → return truereturnupordownorleftorrightdefisPathPossible(mat):n=len(mat)# Visited array to avoid revisiting same cellvisited=[[Falsefor_inrange(n)]for_inrange(n)]# Find the source cell (value = 1)foriinrange(n):forjinrange(n):ifmat[i][j]==1:returndfs(mat,i,j,visited)returnFalseif__name__=="__main__":mat=[[0,3,1,0],[3,0,3,3],[2,3,0,3],[0,3,3,3]]# Check if path existsres=isPathPossible(mat)print(str(res).lower())
C#
usingSystem;classGFG{// Function to check whether a cell is within matrix boundsstaticboolisSafe(intx,inty,intn){return(x>=0&&x<n&&y>=0&&y<n);}// DFS function to explore all possible pathsstaticbooldfs(int[,]mat,intx,inty,bool[,]visited){intn=mat.GetLength(0);// If out of bounds, or wall, or already visited → invalid pathif(!isSafe(x,y,n)||mat[x,y]==0||visited[x,y])returnfalse;// If destination cell is found → return trueif(mat[x,y]==2)returntrue;// Mark current cell as visitedvisited[x,y]=true;// Explore all 4 directions (up, down, left, right)boolup=dfs(mat,x-1,y,visited);booldown=dfs(mat,x+1,y,visited);boolleft=dfs(mat,x,y-1,visited);boolright=dfs(mat,x,y+1,visited);// If any direction leads to destination → return truereturnup||down||left||right;}staticboolisPathPossible(int[,]mat){intn=mat.GetLength(0);// Visited array to avoid revisiting same cellbool[,]visited=newbool[n,n];// Find the source cell (value = 1)for(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i,j]==1){returndfs(mat,i,j,visited);}}}returnfalse;}staticvoidMain(string[]args){int[,]mat={{0,3,1,0},{3,0,3,3},{2,3,0,3},{0,3,3,3}};// Check if path existsboolres=isPathPossible(mat);Console.WriteLine(res.ToString().ToLower());}}
JavaScript
// Function to check whether a cell is within matrix boundsfunctionisSafe(x,y,n){return(x>=0&&x<n&&y>=0&&y<n);}// DFS function to explore all possible pathsfunctiondfs(mat,x,y,visited){letn=mat.length;// If out of bounds, or wall, or already visited → invalid pathif(!isSafe(x,y,n)||mat[x][y]==0||visited[x][y])returnfalse;// If destination cell is found → return trueif(mat[x][y]==2)returntrue;// Mark current cell as visitedvisited[x][y]=true;// Explore all 4 directions (up, down, left, right)letup=dfs(mat,x-1,y,visited);letdown=dfs(mat,x+1,y,visited);letleft=dfs(mat,x,y-1,visited);letright=dfs(mat,x,y+1,visited);// If any direction leads to destination → return truereturnup||down||left||right;}// Main function to check if path exists from source to destinationfunctionisPathPossible(mat){letn=mat.length;// Visited array to avoid revisiting same cellletvisited=Array.from({length:n},()=>Array(n).fill(false));// Find the source cell (value = 1)for(leti=0;i<n;i++){for(letj=0;j<n;j++){if(mat[i][j]==1){returndfs(mat,i,j,visited);}}}returnfalse;}// Drive codeletmat=[[0,3,1,0],[3,0,3,3],[2,3,0,3],[0,3,3,3]];// Check if path existsletres=isPathPossible(mat);console.log(res);
Output
true
[Better Approach] BFS (Graph/Level Order Traversal) - O(n^2) Time and O(n^2) Space
The idea is to treat each cell of the matrix as a node in a graph and connect it with its adjacent cells (up, down, left, right) if movement is allowed. We first convert the matrix into a graph representation where each valid cell becomes a vertex. Then we perform Breadth First Search (BFS) starting from the source cell. If during traversal we reach the destination cell, we return true; otherwise, if BFS finishes without reaching it, we return false.
C++
usingnamespacestd;classGraph{public:intV;vector<vector<int>>adj;// Constructor to initialize graph with V verticesGraph(intV){this->V=V;adj.resize(V);}// Function to add edge between nodesvoidaddEdge(ints,intd){adj[s].push_back(d);}// BFS to check if path exists from source to destinationboolBFS(ints,intd){// If source is same as destinationif(s==d)returntrue;vector<bool>visited(V,false);queue<int>q;// Start BFS from source nodevisited[s]=true;q.push(s);while(!q.empty()){intnode=q.front();q.pop();// Traverse all adjacent nodesfor(intnext:adj[node]){// If destination is reachedif(next==d)returntrue;// If not visited, mark and push to queueif(!visited[next]){visited[next]=true;q.push(next);}}}// Destination not reachablereturnfalse;}};// Function to check boundary and valid cellboolisSafe(inti,intj,intN,vector<vector<int>>&mat){return(i>=0&&i<N&&j>=0&&j<N&&mat[i][j]!=0);}boolisPathPossible(vector<vector<int>>&mat){intN=mat.size();// total nodesintV=N*N+1;Graphg(V);ints=-1,d=-1;// node indexing starts from 1intk=1;// Build graph from matrixfor(inti=0;i<N;i++){for(intj=0;j<N;j++){// If cell is not blockedif(mat[i][j]!=0){// Right neighborif(isSafe(i,j+1,N,mat))g.addEdge(k,k+1);// Left neighborif(isSafe(i,j-1,N,mat))g.addEdge(k,k-1);// Down neighborif(isSafe(i+1,j,N,mat))g.addEdge(k,k+N);// Up neighborif(isSafe(i-1,j,N,mat))g.addEdge(k,k-N);}// Store source cellif(mat[i][j]==1)s=k;// Store destination cellif(mat[i][j]==2)d=k;k++;}}// Run BFS to check reachabilityreturng.BFS(s,d);}intmain(){vector<vector<int>>mat={{0,3,0,1},{3,0,3,3},{2,3,3,3},{0,3,3,3}};cout<<(isPathPossible(mat)?"true":"false")<<endl;return0;}
Java
importjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;classGraph{intV;List<List<Integer>>adj;// Constructor to initialize graph with V verticesGraph(intV){this.V=V;adj=newArrayList<>();for(inti=0;i<V;i++){adj.add(newArrayList<>());}}// Function to add edge between nodesvoidaddEdge(ints,intd){adj.get(s).add(d);}// BFS to check if path exists from source to destinationbooleanBFS(ints,intd){// If source is same as destinationif(s==d)returntrue;boolean[]visited=newboolean[V];Queue<Integer>q=newLinkedList<>();// Start BFS from source nodevisited[s]=true;q.add(s);while(!q.isEmpty()){intnode=q.poll();// Traverse all adjacent nodesfor(intnext:adj.get(node)){// If destination is reachedif(next==d)returntrue;// If not visited, mark and push to queueif(!visited[next]){visited[next]=true;q.add(next);}}}// Destination not reachablereturnfalse;}}classGFG{// Function to check boundary and valid cellstaticbooleanisSafe(inti,intj,intN,int[][]mat){return(i>=0&&i<N&&j>=0&&j<N&&mat[i][j]!=0);}staticbooleanisPathPossible(int[][]mat){intN=mat.length;// total nodesintV=N*N+1;Graphg=newGraph(V);ints=-1,d=-1;// node indexing starts from 1intk=1;// Build graph from matrixfor(inti=0;i<N;i++){for(intj=0;j<N;j++){// If cell is not blockedif(mat[i][j]!=0){// Right neighborif(isSafe(i,j+1,N,mat))g.addEdge(k,k+1);// Left neighborif(isSafe(i,j-1,N,mat))g.addEdge(k,k-1);// Down neighborif(isSafe(i+1,j,N,mat))g.addEdge(k,k+N);// Up neighborif(isSafe(i-1,j,N,mat))g.addEdge(k,k-N);}// Store source cellif(mat[i][j]==1)s=k;// Store destination cellif(mat[i][j]==2)d=k;k++;}}// Run BFS to check reachabilityreturng.BFS(s,d);}publicstaticvoidmain(String[]args){int[][]mat={{0,3,0,1},{3,0,3,3},{2,3,3,3},{0,3,3,3}};System.out.println(isPathPossible(mat));}}
Python
fromcollectionsimportdequeclassGraph:# Constructor to initialize graph with V verticesdef__init__(self,V):self.V=Vself.adj=[[]for_inrange(V)]# Function to add edge between nodesdefaddEdge(self,s,d):self.adj[s].append(d)# BFS to check if path exists from source to destinationdefBFS(self,s,d):# If source is same as destinationifs==d:returnTruevisited=[False]*self.Vq=deque()# Start BFS from source nodevisited[s]=Trueq.append(s)whileq:node=q.popleft()# Traverse all adjacent nodesfornext_nodeinself.adj[node]:# If destination is reachedifnext_node==d:returnTrue# If not visited, mark and push to queueifnotvisited[next_node]:visited[next_node]=Trueq.append(next_node)# Destination not reachablereturnFalse# Function to check boundary and valid celldefisSafe(i,j,N,mat):return(0<=i<Nand0<=j<Nandmat[i][j]!=0)defisPathPossible(mat):N=len(mat)# total nodesV=N*N+1g=Graph(V)s=d=-1# node indexing starts from 1k=1# Build graph from matrixforiinrange(N):forjinrange(N):# If cell is not blockedifmat[i][j]!=0:# Right neighborifisSafe(i,j+1,N,mat):g.addEdge(k,k+1)# Left neighborifisSafe(i,j-1,N,mat):g.addEdge(k,k-1)# Down neighborifisSafe(i+1,j,N,mat):g.addEdge(k,k+N)# Up neighborifisSafe(i-1,j,N,mat):g.addEdge(k,k-N)# Store source cellifmat[i][j]==1:s=k# Store destination cellifmat[i][j]==2:d=kk+=1# Run BFS to check reachabilityreturng.BFS(s,d)if__name__=="__main__":mat=[[0,3,0,1],[3,0,3,3],[2,3,3,3],[0,3,3,3]]print(str(isPathPossible(mat)).lower())
C#
usingSystem;usingSystem.Collections.Generic;classGraph{publicintV;publicList<List<int>>adj;// Constructor to initialize graph with V verticespublicGraph(intV){this.V=V;adj=newList<List<int>>();for(inti=0;i<V;i++){adj.Add(newList<int>());}}// Function to add edge between nodespublicvoidAddEdge(ints,intd){adj[s].Add(d);}// BFS to check if path exists from source to destinationpublicboolBFS(ints,intd){// If source is same as destinationif(s==d)returntrue;bool[]visited=newbool[V];Queue<int>q=newQueue<int>();// Start BFS from source nodevisited[s]=true;q.Enqueue(s);while(q.Count>0){intnode=q.Dequeue();// Traverse all adjacent nodesforeach(intnextinadj[node]){// If destination is reachedif(next==d)returntrue;// If not visited, mark and push to queueif(!visited[next]){visited[next]=true;q.Enqueue(next);}}}// Destination not reachablereturnfalse;}}classGFG{// Function to check boundary and valid cellstaticboolIsSafe(inti,intj,intN,int[,]mat){return(i>=0&&i<N&&j>=0&&j<N&&mat[i,j]!=0);}staticboolIsPathPossible(int[,]mat){intN=mat.GetLength(0);// total nodesintV=N*N+1;Graphg=newGraph(V);ints=-1,d=-1;// node indexing starts from 1intk=1;// Build graph from matrixfor(inti=0;i<N;i++){for(intj=0;j<N;j++){// If cell is not blockedif(mat[i,j]!=0){// Right neighborif(IsSafe(i,j+1,N,mat))g.AddEdge(k,k+1);// Left neighborif(IsSafe(i,j-1,N,mat))g.AddEdge(k,k-1);// Down neighborif(IsSafe(i+1,j,N,mat))g.AddEdge(k,k+N);// Up neighborif(IsSafe(i-1,j,N,mat))g.AddEdge(k,k-N);}// Store source cellif(mat[i,j]==1)s=k;// Store destination cellif(mat[i,j]==2)d=k;k++;}}// Run BFS to check reachabilityreturng.BFS(s,d);}publicstaticvoidMain(){int[,]mat={{0,3,0,1},{3,0,3,3},{2,3,3,3},{0,3,3,3}};Console.WriteLine(IsPathPossible(mat));}}
JavaScript
classGraph{constructor(V){// Constructor to initialize graph with V verticesthis.V=V;this.adj=Array.from({length:V},()=>[]);}// Function to add edge between nodesaddEdge(s,d){this.adj[s].push(d);}// BFS to check if path exists from source to destinationBFS(s,d){// If source is same as destinationif(s===d)returntrue;letvisited=Array(this.V).fill(false);letq=[];// Start BFS from source nodevisited[s]=true;q.push(s);while(q.length>0){letnode=q.shift();// Traverse all adjacent nodesfor(letnextofthis.adj[node]){// If destination is reachedif(next===d)returntrue;// If not visited, mark and push to queueif(!visited[next]){visited[next]=true;q.push(next);}}}// Destination not reachablereturnfalse;}}// Function to check boundary and valid cellfunctionisSafe(i,j,N,mat){return(i>=0&&i<N&&j>=0&&j<N&&mat[i][j]!==0);}functionisPathPossible(mat){letN=mat.length;// total nodesletV=N*N+1;letg=newGraph(V);lets=-1,d=-1;// node indexing starts from 1letk=1;// Build graph from matrixfor(leti=0;i<N;i++){for(letj=0;j<N;j++){// If cell is not blockedif(mat[i][j]!==0){// Right neighborif(isSafe(i,j+1,N,mat))g.addEdge(k,k+1);// Left neighborif(isSafe(i,j-1,N,mat))g.addEdge(k,k-1);// Down neighborif(isSafe(i+1,j,N,mat))g.addEdge(k,k+N);// Up neighborif(isSafe(i-1,j,N,mat))g.addEdge(k,k-N);}// Store source cellif(mat[i][j]===1)s=k;// Store destination cellif(mat[i][j]===2)d=k;k++;}}// Run BFS to check reachabilityreturng.BFS(s,d);}// Driver codeletmat=[[0,3,0,1],[3,0,3,3],[2,3,3,3],[0,3,3,3]];console.log(isPathPossible(mat));
Output
true
[Expected Approach ] BFS (Matrix Traversal without Visited Array) - O(n²) Time and O(1) Space
This approach directly performs BFS on the matrix without using a separate visited array. Instead, visited cells are marked by modifying their values in the matrix.
Find the source cell (value 1) and push it into a queue
Define four possible movement directions (up, down, left, right)
Perform BFS traversal using the queue
For each popped cell, check if it is the destination (2) and return true
Explore all valid neighboring cells (within bounds and not a wall 0)
Mark visited cells by updating their value (e.g., change to 1)
Push valid neighbors into the queue
If BFS finishes without finding the destination, return false
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to check whether the cell is within matrix boundsboolisValid(intx,inty,intn,intm){return(x>=0&&x<n&&y>=0&&y<m);}boolisPathPossible(vector<vector<int>>&mat){intn=mat.size();intm=mat[0].size();// queue for BFS traversalqueue<pair<int,int>>q;// push source cell(s)for(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i][j]==1){q.push({i,j});}}}intdx[4]={-1,0,1,0};intdy[4]={0,-1,0,1};while(!q.empty()){intx=q.front().first;inty=q.front().second;q.pop();// explore 4 directionsfor(inti=0;i<4;i++){intnx=x+dx[i];intny=y+dy[i];// check boundaryif(isValid(nx,ny,n,m)){// destination foundif(mat[nx][ny]==2)returntrue;// visit valid path cellif(mat[nx][ny]==3){// mark visitedmat[nx][ny]=1;q.push({nx,ny});}}}}returnfalse;}intmain(){vector<vector<int>>mat={{0,3,0,1},{3,0,3,3},{2,3,0,3},{0,3,3,3}};cout<<(isPathPossible(mat)?"true":"false")<<endl;return0;}
Java
importjava.io.*;importjava.util.*;classGFG{// Function to check whether the cell is within matrix boundsstaticbooleanisValid(intx,inty,intn,intm){return(x>=0&&x<n&&y>=0&&y<m);}staticbooleanisPathPossible(int[][]mat){intn=mat.length;intm=mat[0].length;// queue for BFS traversalQueue<int[]>q=newLinkedList<>();// push source cell(s)for(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i][j]==1){q.add(newint[]{i,j});}}}int[]dx={-1,0,1,0};int[]dy={0,-1,0,1};while(!q.isEmpty()){int[]cell=q.poll();intx=cell[0];inty=cell[1];// explore 4 directionsfor(inti=0;i<4;i++){intnx=x+dx[i];intny=y+dy[i];// check boundaryif(isValid(nx,ny,n,m)){// destination foundif(mat[nx][ny]==2)returntrue;// visit valid path cellif(mat[nx][ny]==3){// mark visitedmat[nx][ny]=1;q.add(newint[]{nx,ny});}}}}returnfalse;}publicstaticvoidmain(String[]args){int[][]mat={{0,3,0,1},{3,0,3,3},{2,3,0,3},{0,3,3,3}};System.out.println(isPathPossible(mat));}}
Python
fromcollectionsimportdeque# Function to check whether the cell is within matrix boundsdefisValid(x,y,n,m):return(x>=0andx<nandy>=0andy<m)defisPathPossible(mat):n=len(mat)m=len(mat[0])# queue for BFS traversalq=deque()# push source cell(s)foriinrange(n):forjinrange(m):ifmat[i][j]==1:q.append((i,j))dx=[-1,0,1,0]dy=[0,-1,0,1]whileq:x,y=q.popleft()# explore 4 directionsforiinrange(4):nx=x+dx[i]ny=y+dy[i]# check boundaryifisValid(nx,ny,n,m):# destination foundifmat[nx][ny]==2:returnTrue# visit valid path cellifmat[nx][ny]==3:# mark visitedmat[nx][ny]=1q.append((nx,ny))returnFalsemat=[[0,3,0,1],[3,0,3,3],[2,3,0,3],[0,3,3,3]]print(str(isPathPossible(mat)).lower())
C#
usingSystem;usingSystem.Collections.Generic;classGFG{// Function to check whether the cell is within matrix boundsstaticboolisValid(intx,inty,intn,intm){return(x>=0&&x<n&&y>=0&&y<m);}staticboolisPathPossible(int[][]mat){intn=mat.Length;intm=mat[0].Length;// queue for BFS traversalQueue<Tuple<int,int>>q=newQueue<Tuple<int,int>>();// push source cell(s)for(inti=0;i<n;i++){for(intj=0;j<m;j++){if(mat[i][j]==1){q.Enqueue(Tuple.Create(i,j));}}}int[]dx={-1,0,1,0};int[]dy={0,-1,0,1};while(q.Count>0){varcell=q.Dequeue();intx=cell.Item1;inty=cell.Item2;// explore 4 directionsfor(inti=0;i<4;i++){intnx=x+dx[i];intny=y+dy[i];// check boundaryif(isValid(nx,ny,n,m)){// destination foundif(mat[nx][ny]==2)returntrue;// visit valid path cellif(mat[nx][ny]==3){// mark visitedmat[nx][ny]=1;q.Enqueue(Tuple.Create(nx,ny));}}}}returnfalse;}staticvoidMain(){int[][]mat=newint[][]{newint[]{0,3,0,1},newint[]{3,0,3,3},newint[]{2,3,0,3},newint[]{0,3,3,3}};Console.WriteLine(isPathPossible(mat).ToString().ToLower());}}
JavaScript
// Function to check whether the cell is within matrix boundsfunctionisValid(x,y,n,m){return(x>=0&&x<n&&y>=0&&y<m);}functionisPathPossible(mat){letn=mat.length;letm=mat[0].length;// queue for BFS traversalletq=[];// push source cell(s)for(leti=0;i<n;i++){for(letj=0;j<m;j++){if(mat[i][j]===1){q.push([i,j]);}}}letdx=[-1,0,1,0];letdy=[0,-1,0,1];while(q.length>0){let[x,y]=q.shift();// explore 4 directionsfor(leti=0;i<4;i++){letnx=x+dx[i];letny=y+dy[i];// check boundaryif(isValid(nx,ny,n,m)){// destination foundif(mat[nx][ny]===2)returntrue;// visit valid path cellif(mat[nx][ny]===3){// mark visitedmat[nx][ny]=1;q.push([nx,ny]);}}}}returnfalse;}// Driver codeletmat=[[0,3,0,1],[3,0,3,3],[2,3,0,3],[0,3,3,3]];console.log(isPathPossible(mat).toString());