Skip to content

3248. Snake in Matrix 👍

  • Time: O(commands)O(|\texttt{commands}|)
  • Space: O(1)O(1)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int finalPositionOfSnake(int n, vector<string>& commands) {
    const unordered_map<string, pair<int, int>> directions = {
        {"UP", {-1, 0}},
        {"RIGHT", {0, 1}},
        {"DOWN", {1, 0}},
        {"LEFT", {0, -1}}};
    int i = 0;
    int j = 0;

    for (const string& command : commands) {
      const auto& [dx, dy] = directions.at(command);
      i += dx;
      j += dy;
    }

    return i * n + j;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int finalPositionOfSnake(int n, List<String> commands) {
    Map<String, int[]> directions = Map.of("UP", new int[] {-1, 0},   //
                                           "RIGHT", new int[] {0, 1}, //
                                           "DOWN", new int[] {1, 0},  //
                                           "LEFT", new int[] {0, -1});
    int i = 0;
    int j = 0;

    for (final String command : commands) {
      int[] direction = directions.get(command);
      i += direction[0];
      j += direction[1];
    }

    return i * n + j;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def finalPositionOfSnake(self, n: int, commands: list[str]) -> int:
    directions = {
        "UP": (-1, 0),
        "RIGHT": (0, 1),
        "DOWN": (1, 0),
        "LEFT": (0, -1),
    }
    i = 0
    j = 0

    for command in commands:
      dx, dy = directions[command]
      i += dx
      j += dy

    return i * n + j
Was this page helpful?