Maze With N doors and 1 Key | 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 ; Key has been used before ; If current cell is the destination ; Either go down or right ; Driver code ; If there is a path from the cell ( 0 , 0 )
def findPath ( maze , xpos , ypos , key ) : NEW_LINE INDENT if xpos < 0 or xpos >= len ( maze ) or ypos < 0 or ypos >= len ( maze ) : NEW_LINE INDENT return False NEW_LINE DEDENT if maze [ xpos ] [ ypos ] == '1' : NEW_LINE INDENT if key == True : NEW_LINE INDENT if xpos == len ( maze ) - 1 and ypos == len ( maze ) - 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return findPath ( maze , xpos + 1 , ypos , False ) or findPath ( maze , xpos , ypos + 1 , False ) NEW_LINE DEDENT return False NEW_LINE DEDENT if xpos == len ( maze ) - 1 and ypos == len ( maze ) - 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return findPath ( maze , xpos + 1 , ypos , key ) or findPath ( maze , xpos , ypos + 1 , key ) NEW_LINE DEDENT def mazeProb ( maze , xpos , ypos ) : NEW_LINE INDENT key = True NEW_LINE if findPath ( maze , xpos , ypos , key ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT maze = [ [ '0' , '0' , '1' ] , [ '1' , '0' , '1' ] , [ '1' , '1' , '0' ] ] NEW_LINE n = len ( maze ) NEW_LINE if mazeProb ( maze , 0 , 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT