Skip to main content
Back to problems
#353
Medium Algorithms

Design snake game

Array Hash Table Design Queue Simulation
40.0% acceptance
Mar 31, 2026
1015
353

No description available.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::{HashSet, VecDeque};

struct SnakeGame {
  width: i32,
  height: i32,
  food: Vec<Vec<i32>>,
  food_idx: usize,
  body: VecDeque<(i32, i32)>,
  body_set: HashSet<(i32, i32)>,
  score: i32,
}

impl SnakeGame {
  fn new(width: i32, height: i32, food: Vec<Vec<i32>>) -> Self {
    let mut body = VecDeque::new();
    let mut body_set = HashSet::new();
    body.push_back((0, 0));
    body_set.insert((0, 0));
    SnakeGame {
      width,
      height,
      food,
      food_idx: 0,
      body,
      body_set,
      score: 0,
    }
  }

  fn make_a_move(&mut self, direction: String) -> i32 {
    let (hr, hc) = *self.body.front().unwrap();
    let (dr, dc) = match direction.as_str() {
      "U" => (-1, 0),
      "D" => (1, 0),
      "L" => (0, -1),
      "R" => (0, 1),
      _ => return -1,
    };
    let nr = hr + dr;
    let nc = hc + dc;
    if nr < 0 || nr >= self.height || nc < 0 || nc >= self.width {
      return -1;
    }
    if self.food_idx < self.food.len()
      && nr == self.food[self.food_idx][0]
      && nc == self.food[self.food_idx][1]
    {
      self.food_idx += 1;
      self.score += 1;
    } else {
      let tail = self.body.pop_back().unwrap();
      self.body_set.remove(&tail);
    }
    if self.body_set.contains(&(nr, nc)) {
      return -1;
    }
    self.body.push_front((nr, nc));
    self.body_set.insert((nr, nc));
    self.score
  }
}