Find if a 2 | C ++ program for the above approach ; function which tells all cells are visited or not ; starting cell values ; if we get { 0 , 0 } before the end of loop then returns false . Because it means we didn 't traverse all the cells ; If found cycle then return false ; Update startx and starty values to next cell values ; finally if we reach our goal then returns true ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isAllCellTraversed ( vector < vector < pair < int , int > > > grid , int n , int m ) { bool visited [ n ] [ m ] ; int total = n * m ; int startx = grid [ 0 ] [ 0 ] . first ; int starty = grid [ 0 ] [ 0 ] . second ; for ( int i = 0 ; i < total - 2 ; i ++ ) { if ( grid [ startx ] [ starty ] . first == -1 and grid [ startx ] [ starty ] . second == -1 ) return false ; if ( visited [ startx ] [ starty ] == true ) return false ; visited [ startx ] [ starty ] = true ; int x = grid [ startx ] [ starty ] . first ; int y = grid [ startx ] [ starty ] . second ; startx = x ; starty = y ; } if ( grid [ startx ] [ starty ] . first == -1 and grid [ startx ] [ starty ] . second == -1 ) return true ; return false ; } int main ( ) { vector < vector < pair < int , int > > > cell ( 3 , vector < pair < int , int > > ( 2 ) ) ; cell [ 0 ] [ 0 ] = { 0 , 1 } ; cell [ 0 ] [ 1 ] = { 2 , 0 } ; cell [ 1 ] [ 0 ] = { -1 , -1 } ; cell [ 1 ] [ 1 ] = { 1 , 0 } ; cell [ 2 ] [ 0 ] = { 2 , 1 } ; cell [ 2 ] [ 1 ] = { 1 , 1 } ; if ( ! isAllCellTraversed ( cell , 3 , 2 ) ) cout << " true " ; else cout << " false " ; return 0 ; }