# [3248\. Snake in Matrix](https://leetcode.com/problems/snake-in-matrix/) :::spoiler Solution ```cpp= class Solution { public: int finalPositionOfSnake(int n, vector<string>& commands) { int r = 0, c = 0; for (int i = 0; i < commands.size(); i++) { if (commands[i] == "RIGHT" && r < n - 1) { r++; } else if (commands[i] == "LEFT" && r > 0) { r--; } else if (commands[i] == "DOWN" && c < n - 1) { c++; } else if (commands[i] == "UP" && c > 0) { c--; } } return (c * n) + r; } }; ``` - T: $O(n)$ - S: $O(1)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up