# Dynamic Programming – Count all paths in 2D Matrix with Obstructions in it

Objective: Given two dimensional matrix, write an algorithm to count all possible paths from top left corner to bottom-right corner. You are allowed to move only in two directions, move right OR move down. There are few obstructions as well, means few cells are blocked and you cannot travel that cell.

Many times this problem is being referred as “Robot Travel Problem“. Given a 2d matrix, how many ways a robot can travel from top left corner to bottom right corner and there are few cells in which robot cannot travel.

Example: Approach:

• This problem is the extension of the problem “Count all paths from top left to bottom right of a mXn matrix“.
• All we need to take care if one extra condition that we cannot travel to the blocked cells.
• In recursive solution given in “Count all paths from top left to bottom right of a mXn matrix” just check for condition if cell is not blocked.
• In Dynamic programming solution, we need to take care of two conditions, first we are not solving it for blocked cells and while solving for other cells do not involve blocked cells.
• See the code for better understanding.

Code:

 public class NoOfPathObstruction { public int count(int [][] arrA, int row, int col){ //base case //check if last cell is reached since after that only one path if(row==arrA.length–1 && col==arrA.length–1){ return 1; } int right =0; int down = 0; if(row!=arrA.length–1 && arrA[row+1][col]!=–1){ right = count(arrA, row+1, col); } if(col!=arrA.length–1 && arrA[row][col+1]!=–1){ down = count(arrA, row, col+1); } return right + down; } public int countDP(int [][] arrA){ int result [][] = arrA; for (int i = 1; i 0) result[i][j]+=result[i–1][j]; if(result[i][j–1]>0) result[i][j]+=result[i][j–1]; } } } return result[arrA.length–1][arrA.length–1]; } public static void main(String[] args) { int arrA [][] = {{1,1,1},{1,–1,1},{1,–1,1}}; NoOfPathObstruction noOfPaths = new NoOfPathObstruction(); System.out.println("No Of Path (Recursion):- " +noOfPaths.count(arrA,0,0)); System.out.println("No Of Path (DP):- " +noOfPaths.countDP(arrA)); } }

Output:

```No Of Path (Recursion):- 1
No Of Path (DP):- 1
```