Tough Guy

Interview

Time limit1sMemory limit256 MB

Summary
Count the cells reachable from a start on a grid where you move up and down freely but left and right at most L and R times total, with walls blocked.
Level

Medium6 of 10

Topics
Graph, BFS, Array, Shortest path
Solved
No attempts yet

Problem

Yeongjo, the toughest guy at CTP, likes to move around freely. But because he is a tough guy, he only moves up and down. He can move up and down as much as he wants, but he does not move left or right. His friend Boseong, frustrated by Yeongjo's behavior, tags along to stop him from going only up and down and helps him move left at most L times and right at most R times. Yeongjo and Boseong never leave the map.

Given the map information (walkable ground, wall positions, and the starting positions of Yeongjo and Boseong), find the number of all cells they can reach by moving from the starting position.

The following is the figure for example 1 to aid understanding.

The cells Yeongjo and Boseong can reach from the starting position are blue, and cells they cannot reach because of walls are black.

The following figure shows the state after Yeongjo and Boseong move one cell to the left from the starting position.

Since they moved one cell to the left, they can no longer go left, and the paths they can take in the current state are shown in blue.

The following figure shows the state after Yeongjo and Boseong go down from the starting position.

The reachable cells and the current state after Yeongjo and Boseong move one cell down.

The following figure shows the reachable cells when Yeongjo and Boseong move freely.

When Yeongjo and Boseong move freely with at most L moves to the left and R moves to the right, the number of reachable cells is 13.

Input

The first line gives the map's number of rows and columns N, M (1 ≤ N, M ≤ 1,000).

The second line gives the maximum number of moves to the left and to the right L, R (0 ≤ L, R ≤ M).

From the third line to line N+2, the map is given with M characters per row.

  • 0: walkable ground
  • 1: wall, not walkable
  • 2: the position of Yeongjo and Boseong

Output

Print the number of reachable cells, including the starting position.

Examples2

  1. Example 1

    Input
    5 5
    1 1
    00000
    00000
    02100
    10000
    00000
    
    Expected output
    13
    
  2. Example 2

    Input
    4 5
    1 2
    00000
    11010
    02011
    10000
    
    Expected output
    10