Skip to main content
Back to problems
#3248
Easy Algorithms

Snake in matrix

Array String Simulation
82.3% acceptance
Feb 25, 2026
175
4
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn final_position_of_snake(n: i32, commands: Vec<String>) -> i32 {
    let n = n as usize;
    let mut row = 0usize;
    let mut col = 0usize;
    for cmd in &commands {
      match cmd.as_str() {
        "UP"    => row -= 1,
        "DOWN"  => row += 1,
        "LEFT"  => col -= 1,
        "RIGHT" => col += 1,
        _       => {}
      }
    }
    (row * n + col) as i32
  }
}