There is a snake in an n x n matrix grid and can move in four possible directions. Each cell in the grid is identified by the position:
grid[i][j] = (i * n) + j.
The snake starts at cell 0 and follows a sequence of commands.
You are given an integer n representing the size of the grid and an array of strings commands where each command[i] is either "UP", "RIGHT",
"DOWN", and "LEFT". It’s guaranteed that the snake will remain within the
grid boundaries throughout its movement.
Return the position of the final cell where the snake ends up after executing
commands.
The snake’s movement can be simulated by tracking its current position (row, col) and updating it according to each command. Since the grid is small and the commands are guaranteed to keep the snake within bounds, we can use a simple direction-to-delta mapping.
classSolution {
public:int finalCell(int n, vector<string>& cmds) {
int r =0, c =0;
for (auto& s : cmds) {
if (s =="UP") r--;
elseif (s =="DOWN") r++;
elseif (s =="LEFT") c--;
elseif (s =="RIGHT") c++;
}
return r * n + c;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcfinalCell(nint, cmds []string) int {
r, c:=0, 0for_, s:=rangecmds {
switchs {
case"UP": r--case"DOWN": r++case"LEFT": c--case"RIGHT": c++ }
}
returnr*n+c}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintfinalCell(int n, String[] cmds) {
int r = 0, c = 0;
for (String s : cmds) {
if (s.equals("UP")) r--;
elseif (s.equals("DOWN")) r++;
elseif (s.equals("LEFT")) c--;
elseif (s.equals("RIGHT")) c++;
}
return r * n + c;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funfinalCell(n: Int, cmds: Array<String>): Int {
var r = 0; var c = 0for (s in cmds) {
when (s) {
"UP"-> r--"DOWN"-> r++"LEFT"-> c--"RIGHT"-> c++ }
}
return r * n + c
}
}
1
2
3
4
5
6
7
8
9
classSolution:
deffinalCell(self, n: int, cmds: list[str]) -> int:
r, c =0, 0for s in cmds:
if s =="UP": r -=1elif s =="DOWN": r +=1elif s =="LEFT": c -=1elif s =="RIGHT": c +=1return r * n + c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnfinal_cell(n: i32, cmds: Vec<String>) -> i32 {
let (mut r, mut c) = (0, 0);
for s in cmds.iter() {
match s.as_str() {
"UP"=> r -=1,
"DOWN"=> r +=1,
"LEFT"=> c -=1,
"RIGHT"=> c +=1,
_ => {}
}
}
r * n + c
}
}