Maze With N doors and 1 Key | Java implementation of the approach ; Recursive function to check whether there is a path from the top left cell to the bottom right cell of the maze ; Check whether the current cell is within the maze ; If key is required to move further ; If the key hasn 't been used before ; If current cell is the destination ; Either go down or right ; If current cell is the destination ; Either go down or right ; Driver code ; We are making these { { '0' , '0' , '1' } , { '1' , '0' , '1' } , { '1' , '1' , '0' } } ; ; If there is a path from the cell ( 0 , 0 )
import java . io . * ; import java . util . ArrayList ; class GFG { static boolean findPath ( ArrayList < ArrayList < Integer > > maze , int xpos , int ypos , boolean key ) { if ( xpos < 0 || xpos >= maze . size ( ) || ypos < 0 || ypos >= maze . size ( ) ) return false ; if ( maze . get ( xpos ) . get ( ypos ) == '1' ) { if ( key == true ) if ( xpos == maze . size ( ) - 1 && ypos == maze . size ( ) - 1 ) return true ; return findPath ( maze , xpos + 1 , ypos , false ) || findPath ( maze , xpos , ypos + 1 , false ) ; } if ( xpos == maze . size ( ) - 1 && ypos == maze . size ( ) - 1 ) return true ; return findPath ( maze , xpos + 1 , ypos , key ) || findPath ( maze , xpos , ypos + 1 , key ) ; } static boolean mazeProb ( ArrayList < ArrayList < Integer > > maze , int xpos , int ypos ) { boolean key = true ; if ( findPath ( maze , xpos , ypos , key ) ) return true ; return false ; } public static void main ( String [ ] args ) { int size = 3 ; ArrayList < ArrayList < Integer > > maze = new ArrayList < ArrayList < Integer > > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { maze . add ( new ArrayList < Integer > ( ) ) ; } maze . get ( 0 ) . add ( 0 ) ; maze . get ( 0 ) . add ( 0 ) ; maze . get ( 0 ) . add ( 1 ) ; maze . get ( 1 ) . add ( 1 ) ; maze . get ( 1 ) . add ( 0 ) ; maze . get ( 1 ) . add ( 1 ) ; maze . get ( 2 ) . add ( 1 ) ; maze . get ( 2 ) . add ( 1 ) ; maze . get ( 2 ) . add ( 0 ) ; if ( mazeProb ( maze , 0 , 0 ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }