#C1400. Matrix Pathfinding with Directional Movement
Matrix Pathfinding with Directional Movement
Matrix Pathfinding with Directional Movement
You are given an n x m matrix, where each cell contains one of the characters \(P\), \(Q\), or \(R\). Each character represents a type of allowed movement from that cell:
- P: You can only move right or down.
- Q: You can only move left or up.
- R: You can move in all four directions (right, down, left, up).
Your task is to determine whether there is a valid path from the top-left corner (cell \((0,0)\)) to the bottom-right corner (cell \((n-1, m-1)\)) following the movement rules given by the characters in each cell.
If such a path exists, output YES
. Otherwise, output NO
.
Note: All movement must remain within the boundaries of the matrix.
inputFormat
The input is read from stdin and has the following format:
n m row1 row2 ... rown
Where n
and m
are integers representing the number of rows and columns of the matrix. Each of the following n
lines contains a string of exactly m
characters (each character is either P
, Q
, or R
), representing one row of the matrix.
outputFormat
Output a single line to stdout containing either YES
if a valid path exists from the top-left to the bottom-right corner, or NO
if not.
3 3
PQQ
RQR
RRR
YES