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.
Example 1:
Input: n = 2, commands = [“RIGHT”,”DOWN”]
Output: 3
Example 2:
Input: n = 3, commands = [“DOWN”,”RIGHT”,”UP”]
Output: 1
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
First attempt : Time complexity O(n)
impl Solution {
pub fn final_position_of_snake(n: i32, commands: Vec<String>) -> i32 {
let mut output: i32 = 0;
let mut initialPosition:Vec<i32> = vec![0,0];
for i in 0..commands.len(){
// println!("command is {} {:?}",i,commands[i]);
if(commands[i] == "RIGHT"){
initialPosition[1] = initialPosition[1] + 1;
}
else if(commands[i] == "DOWN"){
initialPosition[0] = initialPosition[0] + 1;
}
else if(commands[i] == "LEFT"){
initialPosition[1] = initialPosition[1] - 1;
}
else if(commands[i] == "UP"){
initialPosition[0] = initialPosition[0] - 1;
}
else{
println!("It will not come to this");
}
}
//println!(" this is n {} and comamnds are {:?} final positions after operations are {:?}", n, commands, initialPosition);
output = initialPosition[0]*n + initialPosition[1];
return(output)
}
}
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.