# [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)$ :::