Robot Vacuum Cleaner
InterviewTime limit2sMemory limit512 MB
Simulate a robot vacuum that cleans cells, rotating counterclockwise and moving forward or backward, and count how many cells it cleans before stopping.
- Level
Medium4 of 10
- Topics
- Simulation, Implementation, Array, Matrix
- Solved
- No attempts yet
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 rectangle divided into 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 . The westmost cell of the northmost row is , and the eastmost cell of the southmost row is . In other words, is the -th cell from the west in the -th row from the north. Initially, no empty cell has been cleaned.
The robot works as follows.
-
If the current cell has not been cleaned yet, clean it.
-
If none of the cells adjacent to the current cell is an uncleaned empty cell:
- If the robot can move back one cell while keeping its facing direction, it moves back one cell and returns to step 1.
- If the cell behind the robot is a wall so it cannot move back, the robot stops.
-
If at least one of the cells adjacent to the current cell is an uncleaned empty cell:
- Rotate counterclockwise.
- If the cell in front of the robot is an uncleaned empty cell, move forward one cell.
- Return to step 1.
Input
The first line contains the room size and .
The second line contains the coordinates of the robot's starting cell and its initial facing direction . The robot faces north if is , east if is , south if is , and west if is .
Each of the next lines contains values describing the cells. The -th value on the -th of these lines is the state of cell . A value of means is an uncleaned empty cell, and a value of means 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.