Unique Paths with Obstacles
Problem
A robot stands in the top-left cell of a grid and wants to reach the bottom-right cell. It may move only right or down. A cell with 1 is blocked and a cell with 0 is free. Print the number of different paths. If the start or the end is blocked, print 0. Input: rows and columns, then the grid.
Constraints
- 1 <= r, c <= 12
- grid values are 0 or 1
Examples
Input
3 3 0 0 0 0 1 0 0 0 0
Output
2
Solutions
A free cell gets the paths from above plus the paths from the left. Because we go row by row, the number already stored in ways[j] is the one from above. O(r * c) time and O(c) memory.
/*
* Problem : Count robot paths.
* Input : r and c, then the grid.
* Output : Number of paths.
* Approach: One row of counts.
* Time : O(r * c)
* Space : O(c)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[][] m) {
// Step 1: ways[j] is the number of paths to the cell in column j of the current row. We keep one row only.
int columns = m[0].length;
long[] ways = new long[columns];
ways[0] = 1;
for (int[] row : m) {
for (int j = 0; j < columns; j++) {
// Step 2: A blocked cell has no paths. Otherwise add the paths from the left cell. The cell above is already in ways[j].
if (row[j] == 1) {
ways[j] = 0;
} else if (j > 0) {
ways[j] += ways[j - 1];
}
}
}
return ways[columns - 1];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] m = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = scanner.nextInt();
}
}
System.out.println(solve(m));
}
}
Hints (2)
- What does ways[j] hold before we update it?
- What happens at a blocked cell?