Find the total number of unique paths that the robot can take in a given maze to reach a given destination from a given source.

Positions in the maze will either be open or blocked with an obstacle. The robot can only move to positions without obstacles, i.e., the solution should find paths that contain only open cells. Retracing the one or more cells back and forth is not considered a new path. The set of all cells covered in a single path should be unique from other paths. At any given moment, the robot can only move one step in either of the four directions. The valid moves are:

Go North: (x, y) ——> (x – 1, y)
Go West:  (x, y) ——> (x, y – 1)
Go South: (x, y) ——> (x + 1, y)
Go East:  (x, y) ——> (x, y + 1)

For example, consider the following maze in the form of a binary matrix where 0 represents a blocked cell and 1 represents an open cell:

  [ 1  1  1  1 ]
  [ 1  1  0  1 ]
  [ 0  1  0  1 ]
  [ 1  1  1  1 ]

We have to find the total number of unique paths from source to destination. The above maze contains 4 unique paths (marked in blue color).

 [ 1  1  1  1 ]    [ 1  1  1  1 ]
 [ 1  1  0  1 ]    [ 1  1  0  1 ]
 [ 0  1  0  1 ]    [ 0  1  0  1 ]
 [ 1  1  1  1 ]    [ 1  1  1  1 ]
 
 [ 1  1  1  1 ]    [ 1  1  1  1 ]
 [ 1  1  0  1 ]    [ 1  1  0  1 ]
 [ 0  1  0  1 ]    [ 0  1  0  1 ]
 [ 1  1  1  1 ]    [ 1  1  1  1 ]

Practice this problem

The robot should search for a path from the starting position to the goal position until it finds one or until it exhausts all possibilities. We can easily achieve this with the help of Backtracking. We start from the given source cell in the matrix and explore all four paths possible and recursively check if they will lead to the destination or not. We update the unique path count whenever the destination cell is reached. If a path doesn’t reach the destination or explored all possible routes from the current cell, we backtrack. To make sure that the path is simple and doesn’t contain any cycles, keep track of cells involved in the current path in a matrix, and before exploring any cell, ignore the cell if it is already covered in the current path.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of unique paths are 4

Java


Download  Run Code

Output:

The total number of unique paths are 4

Python


Download  Run Code

Output:

The total number of unique paths are 4

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).

 
Exercise: Extend the solution to print the paths as well