#C5709. Simulating Robot Movement on a Grid
Simulating Robot Movement on a Grid
Simulating Robot Movement on a Grid
You are given a rectangular grid with R rows and C columns. Each cell in the grid is either an empty space, denoted by .
, or an obstacle, denoted by #
. A robot is placed at a given initial position on the grid. The robot is then given a sequence of commands, where each command is one of the following: U
(up), D
(down), L
(left), or R
(right).
The robot executes the commands sequentially. For each command, if the robot’s next cell is outside the grid or contains an obstacle, the robot halts and does not execute any further commands. Otherwise, it moves to the new cell.
Your task is to determine the final position of the robot after processing the given commands.
Mathematically, if the robot is at position \((r, c)\) and the next move takes it to \((r', c')\), the move is valid if and only if \[ 0 \leq r' < R \quad \text{and} \quad 0 \leq c' < C \quad \text{and} \quad grid[r'][c'] \neq '#' . \]
inputFormat
The input is given via standard input (stdin) and has the following format:
- The first line contains two integers R and C, representing the number of rows and columns of the grid.
- The next R lines each contain a string of length C representing a row of the grid. The character
.
indicates an empty cell and#
indicates an obstacle. - The following line contains two integers indicating the robot's initial row and column (0-indexed), separated by a space.
- The final line contains a string of commands consisting only of the characters
U
,D
,L
, andR
.
Note: The grid indices start from 0, i.e., the top-left corner is (0, 0).
outputFormat
Output the final position of the robot as two space-separated integers (row and column) on standard output (stdout).
## sample5 5
.....
..#..
.....
.....
.....
2 2
UURRDDLL
2 2