Given a 2D array(m x n). The task is to check if there is any path from top left to bottom right. In the matrix, -1 is considered as blockage (can’t go through this cell) and 0 is considered path cell (can go through it).
Note: Top left cell always contains 0
Examples:
Input : arr[][] = {{ 0, 0, 0, -1, 0},
{-1, 0, 0, -1, -1},
{ 0, 0, 0, -1, 0},
{-1, 0, 0, 0, 0},
{ 0, 0, -1, 0, 0}}
Output : Yes
Explanation:

The red cells are blocked, white cell denotes the path and the green cells are not blocked cells.
Input : arr[][] = {{ 0, 0, 0, -1, 0},
{-1, 0, 0, -1, -1},
{ 0, 0, 0, -1, 0},
{-1, 0, -1, 0, 0},
{ 0, 0, -1, 0, 0}}
Output : No
Explanation: There exists no path from start to end.

The red cells are blocked, white cell denotes the path and the green cells are not blocked cells.
Method 1
- Approach: The solution is to perform BFS or DFS to find whether there is a path or not. The graph needs not to be created to perform the bfs, but the matrix itself will be used as a graph. Start the traversal from the top right corner and if there is a way to reach the bottom right corner then there is a path.
- Algorithm:
- Create a queue that stores pairs (i,j) and insert the (0,0) in the queue.
- Run a loop till the queue is empty.
- In each iteration dequeue the queue (a,b), if the front element is the destination (row-1,col-1) then return 1, i,e there is a path and change the value of mat[a][b] to -1, i.e. visited.
- Else insert the adjacent indices where the value of matrix[i][j] is not -1.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
#define row 5
#define col 5
bool isPath( int arr[row][col])
{
int dir[4][2]
= { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
queue<pair< int , int > > q;
q.push(make_pair(0, 0));
while (q.size() > 0) {
pair< int , int > p = q.front();
q.pop();
arr[p.first][p.second] = -1;
if (p == make_pair(row - 1, col - 1))
return true ;
for ( int i = 0; i < 4; i++) {
int a = p.first + dir[i][0];
int b = p.second + dir[i][1];
if (arr[a][b] != -1 && a >= 0 && b >= 0
&& a < row && b < col) {
q.push(make_pair(a, b));
}
}
}
return false ;
}
int main()
{
int arr[row][col] = { { 0, 0, 0, -1, 0 },
{ -1, 0, 0, -1, -1 },
{ 0, 0, 0, -1, 0 },
{ -1, 0, 0, 0, 0 },
{ 0, 0, -1, 0, 0 } };
if (isPath(arr))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class pair {
int Item1, Item2;
pair( int f, int s)
{
Item1 = f;
Item2 = s;
}
}
class GFG {
static int row = 5 ;
static int col = 5 ;
static boolean isPath( int [][] arr)
{
int [][] dir
= { { 0 , 1 }, { 0 , - 1 }, { 1 , 0 }, { - 1 , 0 } };
Queue<pair> q = new LinkedList<>();
q.add( new pair( 0 , 0 ));
while (q.size() > 0 ) {
pair p = (q.peek());
q.remove();
arr[p.Item1][p.Item2] = - 1 ;
if (p.Item1 == row - 1 && p.Item2 == col - 1 )
return true ;
for ( int i = 0 ; i < 4 ; i++) {
int a = p.Item1 + dir[i][ 0 ];
int b = p.Item2 + dir[i][ 1 ];
if (a >= 0 && b >= 0 && a < row && b < col
&& arr[a][b] != - 1 ) {
if (a == row - 1 && b == col - 1 )
return true ;
q.add( new pair(a, b));
}
}
}
return false ;
}
public static void main(String[] args)
{
int [][] arr = { { 0 , 0 , 0 , - 1 , 0 },
{ - 1 , 0 , 0 , - 1 , - 1 },
{ 0 , 0 , 0 , - 1 , 0 },
{ - 1 , 0 , 0 , 0 , 0 },
{ 0 , 0 , - 1 , 0 , 0 } };
if (isPath(arr))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
row = 5
col = 5
def isPath(arr) :
Dir = [ [ 0 , 1 ], [ 0 , - 1 ], [ 1 , 0 ], [ - 1 , 0 ]]
q = []
q.append(( 0 , 0 ))
while ( len (q) > 0 ) :
p = q[ 0 ]
q.pop( 0 )
arr[p[ 0 ]][p[ 1 ]] = - 1
if (p = = (row - 1 , col - 1 )) :
return True
for i in range ( 4 ) :
a = p[ 0 ] + Dir [i][ 0 ]
b = p[ 1 ] + Dir [i][ 1 ]
if (a > = 0 and b > = 0 and a < row and b < col and arr[a][b] ! = - 1 ) :
q.append((a, b))
return False
arr = [[ 0 , 0 , 0 , - 1 , 0 ],
[ - 1 , 0 , 0 , - 1 , - 1 ],
[ 0 , 0 , 0 , - 1 , 0 ],
[ - 1 , 0 , 0 , 0 , 0 ],
[ 0 , 0 , - 1 , 0 , 0 ] ]
if (isPath(arr)) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class pair {
public int Item1, Item2;
public pair( int f, int s)
{
Item1 = f;
Item2 = s;
}
}
class GFG {
static int row = 5;
static int col = 5;
static bool isPath( int [, ] arr)
{
int [, ] dir
= { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
LinkedList<pair> q = new LinkedList<pair>();
q.AddLast( new pair(0, 0));
while (q.Count > 0) {
pair p = (pair)(q.First.Value);
q.RemoveFirst();
arr[p.Item1, p.Item2] = -1;
if (p.Item1 == row - 1 && p.Item2 == col - 1)
return true ;
for ( int i = 0; i < 4; i++) {
int a = p.Item1 + dir[i, 0];
int b = p.Item2 + dir[i, 1];
if (a >= 0 && b >= 0 && a < row && b < col
&& arr[a, b] != -1) {
if (a == row - 1 && b == col - 1)
return true ;
q.AddLast( new pair(a, b));
}
}
}
return false ;
}
public static void Main( string [] args)
{
int [, ] arr = { { 0, 0, 0, -1, 0 },
{ -1, 0, 0, -1, -1 },
{ 0, 0, 0, -1, 0 },
{ -1, 0, 0, 0, 0 },
{ 0, 0, -1, 0, 0 } };
if (isPath(arr))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
var row = 5;
var col = 5;
function isPath(arr)
{
var dir = [ [ 0, 1 ], [ 0, -1 ],
[ 1, 0 ], [ -1, 0 ] ];
var q = [];
q.push([0, 0]);
while (q.length > 0)
{
var p = q[0];
q.shift();
arr[p[0]][p[1]] = -1;
if (p[0]==row-1 && p[1]==col-1)
return true ;
for ( var i = 0; i < 4; i++)
{
var a = p[0] + dir[i][0];
var b = p[1] + dir[i][1];
if (a >= 0 && b >= 0 &&
a < row && b < col &&
arr[a][b] != -1)
{
if (a==row - 1 && b==col - 1)
return true ;
q.push([a,b]);
}
}
}
return false ;
}
var arr = [[ 0, 0, 0, -1, 0 ],
[ -1, 0, 0, -1, -1],
[ 0, 0, 0, -1, 0 ],
[ -1, 0, 0, 0, 0 ],
[ 0, 0, -1, 0, 0 ] ];
if (isPath(arr))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
- Complexity Analysis:
- Time Complexity: O(R*C).
Every element of the matrix can be inserted once in the queue, so time Complexity is O(R*C).
- Space Complexity: O(R*C).
To store all the elements in a queue O(R*C) space is needed.
Method 2
- Approach: The only problem with the above solution is it uses extra space. This approach will eliminate the need for extra space. The basic idea is very similar. This algorithm will also perform BFS but the need for extra space will be eliminated by marking the array. So First run a loop and check which elements of the first column and the first row is accessible from 0,0 by using only the first row and column. mark them as 1. Now traverse the matrix from start to the end row-wise in increasing index of rows and columns. If the cell is not blocked then check that any of its adjacent cells is marked 1 or not. If marked 1 then mark the cell 1.
- Algorithm:
- Mark the cell 0,0 as 1.
- Run a loop from 0 to row length and if the cell above is marked 1 and the current cell is not blocked then mark the current cell as 1.
- Run a loop from 0 to column length and if the left cell is marked 1 and the current cell is not blocked then mark the current cell as 1.
- Traverse the matrix from start to the end row-wise in increasing index of rows and columns.
- If the cell is not blocked then check that any of its adjacent cells (check only the cell above and the cell to the left). is marked 1 or not. If marked 1 then mark the cell 1.
- If the cell (row-1, col-1) is marked 1 return true else return false.
Implementation:
C++
#include <iostream>
using namespace std;
#define row 5
#define col 5
bool isPath( int arr[row][col])
{
arr[0][0] = 1;
for ( int i = 1; i < row; i++)
if (arr[i][0] != -1)
arr[i][0] = arr[i - 1][0];
for ( int j = 1; j < col; j++)
if (arr[0][j] != -1)
arr[0][j] = arr[0][j - 1];
for ( int i = 1; i < row; i++)
for ( int j = 1; j < col; j++)
if (arr[i][j] != -1)
arr[i][j] = max(arr[i][j - 1],
arr[i - 1][j]);
return (arr[row - 1][col - 1] == 1);
}
int main()
{
int arr[row][col] = { { 0, 0, 0, -1, 0 },
{ -1, 0, 0, -1, -1 },
{ 0, 0, 0, -1, 0 },
{ -1, 0, -1, 0, -1 },
{ 0, 0, -1, 0, 0 } };
if (isPath(arr))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG
{
static boolean isPath( int arr[][])
{
arr[ 0 ][ 0 ] = 1 ;
for ( int i = 1 ; i < 5 ; i++)
if (arr[ 0 ][i] != - 1 )
arr[ 0 ][i] = arr[ 0 ][i - 1 ];
for ( int j = 1 ; j < 5 ; j++)
if (arr[j][ 0 ] != - 1 )
arr[j][ 0 ] = arr[j - 1 ][ 0 ];
for ( int i = 1 ; i < 5 ; i++)
for ( int j = 1 ; j < 5 ; j++)
if (arr[i][j] != - 1 )
arr[i][j] = Math.max(arr[i][j - 1 ],
arr[i - 1 ][j]);
return (arr[ 5 - 1 ][ 5 - 1 ] == 1 );
}
public static void main(String[] args)
{
int arr[][] = { { 0 , 0 , 0 , - 1 , 0 },
{ - 1 , 0 , 0 , - 1 , - 1 },
{ 0 , 0 , 0 , - 1 , 0 },
{ - 1 , 0 , - 1 , 0 , - 1 },
{ 0 , 0 , - 1 , 0 , 0 } };
if (isPath(arr))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
row = 5
col = 5
def isPath(arr):
arr[ 0 ][ 0 ] = 1
for i in range ( 1 , row):
if (arr[i][ 0 ] ! = - 1 ):
arr[i][ 0 ] = arr[i - 1 ][ 0 ]
for j in range ( 1 , col):
if (arr[ 0 ][j] ! = - 1 ):
arr[ 0 ][j] = arr[ 0 ][j - 1 ]
for i in range ( 1 , row):
for j in range ( 1 , col):
if (arr[i][j] ! = - 1 ):
arr[i][j] = max (arr[i][j - 1 ],
arr[i - 1 ][j])
return (arr[row - 1 ][col - 1 ] = = 1 )
arr = [[ 0 , 0 , 0 , - 1 , 0 ],
[ - 1 , 0 , 0 , - 1 , - 1 ],
[ 0 , 0 , 0 , - 1 , 0 ],
[ - 1 , 0 , - 1 , 0 , - 1 ],
[ 0 , 0 , - 1 , 0 , 0 ]]
if (isPath(arr)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isPath( int [,]arr)
{
arr[0, 0] = 1;
for ( int i = 1; i < 5; i++)
if (arr[i, 0] != -1)
arr[i, 0] = arr[i - 1, 0];
for ( int j = 1; j < 5; j++)
if (arr[0,j] != -1)
arr[0,j] = arr[0, j - 1];
for ( int i = 1; i < 5; i++)
for ( int j = 1; j < 5; j++)
if (arr[i, j] != -1)
arr[i, j] = Math.Max(arr[i, j - 1],
arr[i - 1, j]);
return (arr[5 - 1, 5 - 1] == 1);
}
public static void Main()
{
int [,]arr = { { 0, 0, 0, -1, 0 },
{ -1, 0, 0, -1, -1 },
{ 0, 0, 0, -1, 0 },
{ -1, 0, -1, 0, -1 },
{ 0, 0, -1, 0, 0 } };
if (isPath(arr))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
$row = 5;
$col = 5;
function isPath( $arr )
{
global $row , $col ;
$arr [0][0] = 1;
for ( $i = 1; $i < $row ; $i ++)
if ( $arr [ $i ][0] != -1)
$arr [ $i ][0] = $arr [ $i - 1][0];
for ( $j = 1; $j < $col ; $j ++)
if ( $arr [0][ $j ] != -1)
$arr [0][ $j ] = $arr [0][ $j - 1];
for ( $i = 1; $i < $row ; $i ++)
for ( $j = 1; $j < $col ; $j ++)
if ( $arr [ $i ][ $j ] != -1)
$arr [ $i ][ $j ] = max( $arr [ $i ][ $j - 1],
$arr [ $i - 1][ $j ]);
return ( $arr [ $row - 1][ $col - 1] == 1);
}
$arr = array ( array (0, 0, 0, 1, 0),
array (-1, 0, 0, -1, -1),
array (0, 0, 0, -1, 0),
array (-1, 0, -1, 0, -1),
array (0, 0, -1, 0, 0));
if (isPath( $arr ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
var arr = [[5], [5]]
function isPath(arr)
{
arr[0][0] = 1;
for ( var i = 1; i < 5; i++)
if (arr[i][0] != -1)
arr[i][0] = arr[i - 1][0];
for ( var j = 1; j < 5; j++)
if (arr[0][j] != -1)
arr[0][j] = arr[0][j - 1];
for ( var i = 1; i < 5; i++)
for ( var j = 1; j < 5; j++)
if (arr[i][j] != -1)
arr[i][j] = Math.max(arr[i][j - 1],
arr[i - 1][j]);
return (arr[5 - 1][5 - 1] == 1);
}
var arr = [ [ 0, 0, 0, -1, 0 ],
[ -1, 0, 0, -1, -1 ],
[ 0, 0, 0, -1, 0 ],
[ -1, 0, -1, 0, -1 ],
[ 0, 0, -1, 0, 0 ] ];
if (isPath(arr))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
- Complexity Analysis:
- Time Complexity: O(R*C).
Every element of the matrix is traversed, so time Complexity is O(R*C).
- Space Complexity: O(1).
No extra space is needed.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
20 Dec, 2022
Like Article
Save Article