All problems

Problem 190

Unique Paths with Obstacles

Medium · 20 pts · Matrix, Dynamic Programming

Problem

A robot stands in the top-left cell of a grid and wants to reach the bottom-right cell, moving only one cell right or one cell down at a time. Some cells, marked '1', are obstacles that the robot cannot enter. Count the paths that avoid every obstacle, modulo 1000000007. If the start or the end cell is an obstacle, the answer is 0. The same recurrence as for Unique Paths works: paths to a cell = paths to the cell above + paths to the cell on the left, except that an obstacle cell always has 0 paths. Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).

Input

First line: integers R and C. Next R lines: C characters, each '0' (open) or '1' (obstacle).

Output

Print the number of paths modulo 1000000007.

Constraints

1 <= R, C <= 500

Example input

3 3
000
010
000

Example output

2

Explanation

In the 3 x 3 grid with an obstacle in the centre, the robot can only go around it: along the top row and down the right column, or down the left column and along the bottom row. That is 2 paths.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Unique Paths Next: Minimum Path Sum