Check for possible path in 2D matrix | C ++ program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; directions ; queue ; insert the top right corner . ; until queue is empty ; mark as visited ; destination is reached . ; check all four directions ; using the direction array ; not blocked and valid ; Driver Code ; Given array ; path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define row  5 NEW_LINE #define col  5 NEW_LINE 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 , -1 , 0 , -1 } , { 0 , 0 , -1 , 0 , 0 } } ; if ( isPath ( arr ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }