Snake in Matrix
Problem
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.
Examples
Example 1
Input: n = 2, commands = ["RIGHT","DOWN"]
Output: 3
Explanation:
0 | 1
---|---
2 | 3
0 | 1
---|---
2 | 3
0 | 1
---|---
2 | 3
Example 2
Input: n = 3, commands = ["DOWN","RIGHT","UP"]
Output: 1
Explanation:
0 | 1 | 2
---|---|---
3 | 4 | 5
6 | 7 | 8
0 | 1 | 2
---|---|---
3 | 4 | 5
6 | 7 | 8
0 | 1 | 2
---|---|---
3 | 4 | 5
6 | 7 | 8
0 | 1 | 2
---|---|---
3 | 4 | 5
6 | 7 | 8
Constraints
2 <= n <= 101 <= commands.length <= 100commandsconsists only of"UP","RIGHT","DOWN", and"LEFT".- The input is generated such the snake will not move outside of the boundaries.
Solution
Method 1 – Simulate Movement with Direction Mapping
Intuition
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.
Approach
- Start at position (0, 0).
- For each command, update the row or column based on the direction:
- "UP": row -= 1
- "DOWN": row += 1
- "LEFT": col -= 1
- "RIGHT": col += 1
- After all commands, return the final position as (row * n + col).
Code
C++
class Solution {
public:
int finalCell(int n, vector<string>& cmds) {
int r = 0, c = 0;
for (auto& s : cmds) {
if (s == "UP") r--;
else if (s == "DOWN") r++;
else if (s == "LEFT") c--;
else if (s == "RIGHT") c++;
}
return r * n + c;
}
};
Go
func finalCell(n int, cmds []string) int {
r, c := 0, 0
for _, s := range cmds {
switch s {
case "UP": r--
case "DOWN": r++
case "LEFT": c--
case "RIGHT": c++
}
}
return r*n + c
}
Java
class Solution {
public int finalCell(int n, String[] cmds) {
int r = 0, c = 0;
for (String s : cmds) {
if (s.equals("UP")) r--;
else if (s.equals("DOWN")) r++;
else if (s.equals("LEFT")) c--;
else if (s.equals("RIGHT")) c++;
}
return r * n + c;
}
}
Kotlin
class Solution {
fun finalCell(n: Int, cmds: Array<String>): Int {
var r = 0; var c = 0
for (s in cmds) {
when (s) {
"UP" -> r--
"DOWN" -> r++
"LEFT" -> c--
"RIGHT" -> c++
}
}
return r * n + c
}
}
Python
class Solution:
def finalCell(self, n: int, cmds: list[str]) -> int:
r, c = 0, 0
for s in cmds:
if s == "UP": r -= 1
elif s == "DOWN": r += 1
elif s == "LEFT": c -= 1
elif s == "RIGHT": c += 1
return r * n + c
Rust
impl Solution {
pub fn final_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
}
}
TypeScript
class Solution {
finalCell(n: number, cmds: string[]): number {
let r = 0, c = 0;
for (const s of cmds) {
if (s === "UP") r--;
else if (s === "DOWN") r++;
else if (s === "LEFT") c--;
else if (s === "RIGHT") c++;
}
return r * n + c;
}
}
Complexity
- ⏰ Time complexity:
O(m), where m is the number of commands. Each command is processed once. - 🧺 Space complexity:
O(1), only a constant number of variables are used.