Every day a Leetcode
题目来源:3248. 矩阵中的蛇
解法1:模拟
遍历字符串数组 commands,模拟🐍的移动过程。
如果最后🐍的位置为 (i, j),则编号为 (i * n) + j。
代码:
/*
* @lc app=leetcode.cn id=3248 lang=cpp
*
* [3248] 矩阵中的蛇
*/
// @lc code=start
class Solution
{
public:
int finalPositionOfSnake(int n, vector<string> &commands)
{
int i = 0, j = 0;
for (string &cmd : commands)
{
switch (cmd[0])
{
case 'U':
i--;
break;
case 'R':
j++;
break;
case 'D':
i++;
break;
case 'L':
j--;
break;
default:
break;
}
}
return (i * n) + j;
}
};
// @lc code=end
结果:

复杂度分析:
时间复杂度:O(n),其中 n 是字符串数组 commands 的长度。
空间复杂度:O(1)。
![[Hive]五、Hive 源码编译](https://i-blog.csdnimg.cn/direct/1b82ef5360c74109950d8954c08d927e.png)

















