[LeetCode] Snake in Matrix

3248. Snake in Matrix

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int finalPositionOfSnake(int n, vector<string>& commands) {
int y = 0, x = 0;
map<char,pair<int,int>> dir{{'U',{-1,0}},{'D',{1,0}},{'R',{0,1}},{'L',{0,-1}}};
for(auto& c : commands) {
auto [yy,xx] = dir[c[0]];
y += yy, x += xx;
}
int res = y * n + x;
for(int i = 0; i < commands.size(); i++) {
for(auto& c : commands) {
auto [yy,xx] = dir[c[0]];
y += yy, x += xx;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/11/PS/LeetCode/snake-in-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.