Robot Vacuum Cleaner

Simulate a robot vacuum that cleans cells, rotating counterclockwise and moving forward or backward, and count how many cells it cleans before stopping.

Medium4SimulationImplementationArrayMatrixInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

Given a robot vacuum cleaner and the state of a room, write a program that counts the cells the robot cleans.

The room is an N×MN \times M rectangle divided into 1×11 \times 1 square cells. Each cell is either a wall or an empty cell. The robot faces one of four directions: east, west, south, or north. Each cell of the room is written as a coordinate (r,c)(r, c). The westmost cell of the northmost row is (0,0)(0, 0), and the eastmost cell of the southmost row is (N1,M1)(N-1, M-1). In other words, (r,c)(r, c) is the (c+1)(c+1)-th cell from the west in the (r+1)(r+1)-th row from the north. Initially, no empty cell has been cleaned.

The robot works as follows.

  1. If the current cell has not been cleaned yet, clean it.

  2. If none of the 44 cells adjacent to the current cell is an uncleaned empty cell:

    1. If the robot can move back one cell while keeping its facing direction, it moves back one cell and returns to step 1.
    2. If the cell behind the robot is a wall so it cannot move back, the robot stops.
  3. If at least one of the 44 cells adjacent to the current cell is an uncleaned empty cell:

    1. Rotate 9090^\circ counterclockwise.
    2. If the cell in front of the robot is an uncleaned empty cell, move forward one cell.
    3. Return to step 1.

Input

The first line contains the room size NN and MM. (3N,M50)(3 \le N, M \le 50)

The second line contains the coordinates (r,c)(r, c) of the robot's starting cell and its initial facing direction dd. The robot faces north if dd is 00, east if dd is 11, south if dd is 22, and west if dd is 33.

Each of the next NN lines contains MM values describing the cells. The jj-th value on the ii-th of these lines is the state of cell (i,j)(i, j). A value of 00 means (i,j)(i, j) is an uncleaned empty cell, and a value of 11 means (i,j)(i, j) is a wall. Every cell in the northmost, southmost, westmost, or eastmost row or column is a wall. The robot's starting cell is always empty.

Output

Print the number of cells the robot cleans from the moment it starts until it stops.