This page is still under construction.

Parts of this page are still being built. What you see may change.

Box pushing robot

Time limit4sMemory limit512 MB

Summary
Count the grid cells a box can reach when a robot walking on free cells can push it one step at a time from its start.
Level

Medium6 of 10

Topics
BFS, Graph
Solved
No attempts yet

Problem

A factory moves a heavy box with a robot. To move the box in some direction, the robot first has to reach the cell behind the box, then push the box forward in that direction.

The factory floor is an m×nm \times n grid. A cell that holds an obstacle is blocked. The robot and the box each occupy one cell. In the figure on the right, blocked cells are gray, and r and s mark the robot and the box.

A cell is free if it is not blocked and the box is not on it. In one step the robot moves from its current cell to the cell above, below, to the left, or to the right of it, provided that cell is free. If the neighboring cell holds the box, the robot can push the box one cell in the same direction, provided the cell the box enters is free. The robot and the box can never leave the grid.

The box starts at cell s and the robot at cell r. Cell t is reachable from s if some sequence of robot steps pushes the box from s to t. In the figure, the left cell marked t is reachable from s, while the cell marked t' is not. Given the grid and the two starting positions, count how many cells are reachable from s. The cell s itself always counts, even when the robot can never reach the box.

Input

The input holds several test cases. The first line of a test case has two integers m and n (1≤m,n≤10001 \le m, n \le 1000), the number of rows and the number of columns of the grid. Each of the next m lines has a string of length n, where the j-th character of the i-th line is cell (i, j). An obstacle is o, the robot is r, the starting cell of the box is s, and every other cell is -. Each grid has exactly one r and exactly one s. The last line of the input is 0 0 and is not a test case. The sum of m×nm \times n over all test cases is at most 10610^6.

Output

For each test case, print one line with the number of grid cells the box can reach from its starting cell s.

Examples2

  1. Example 1

    Input
    7 7
    o------
    -o-----
    -------
    -oooo--
    -----o-
    ---s---
    r----o-
    3 4
    ---o
    -os-
    ---r
    0 0
    
    Expected output
    21
    6
    
  2. Example 2

    Input
    1 2
    rs
    1 3
    rs-
    1 3
    r-s
    3 3
    ---
    -s-
    r--
    2 1
    r
    s
    0 0
    
    Expected output
    1
    2
    1
    9
    1