Superjump in a grid

4.8

6 votes
Algorithms, Dynamic Programming, 2D dynamic programming
Problem

You are given a NM grid in which each cell consists of either 0 or 1. A cell (i,j) is blocked if its value is 1. Standing at a cell (i,j), you can perform the following steps.

  1. You can move right to the very next cell which is not blocked.
  2. You can move down to the very next cell which is not blocked.

You are initially located at cell (1,1). Determine the number of ways in which you can reach (N,M) starting from your initial location.

Since the answer can be large, print it modulo (109+7).

Example: Let 3 * 3 grid be 

0 1 0
1 0 0
0 0 0

If you are standing at cell (1,1), then:

  • By performing step 1, you can jump to cell (1,3) and, 
  • By performing step 2, you can jump to cell (3,1)

The answer will be 2.

Input format 

  • The first line contains N and M denoting the number of rows and the number of columns.
  • Each of the next N lines consists of a string of length M.

Output format

Print a single line containing the number of ways to reach (N,M) from (1,1) modulo 109+7.

Constraints

1N,M1000

Each cell consists of either '0' or '1'.

Sample Input
3 3
000
011
000

Sample Output
3

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

There are 3 ways to reach (3,3) from (1,1).

  1. (1,1) -> (2,1) -> (3,1) -> (3,2) -> (3,3).
  2. (1,1) -> (1,2) -> (3,2) -> (3,3).
  3. (1,1) -> (1,2) -> (1,3) -> (3,3).
Editor Image

?