您的位置:首页 > 娱乐 > 八卦 > 杭州棋牌软件开发公司_广东省广州市有哪几个区_中国市场营销网_网站设计公司

杭州棋牌软件开发公司_广东省广州市有哪几个区_中国市场营销网_网站设计公司

2024/12/23 6:04:28 来源:https://blog.csdn.net/breaksoftware/article/details/142382851  浏览:    关键词:杭州棋牌软件开发公司_广东省广州市有哪几个区_中国市场营销网_网站设计公司
杭州棋牌软件开发公司_广东省广州市有哪几个区_中国市场营销网_网站设计公司

大纲

  • 题目
    • 地址
    • 内容
  • 解题
    • 代码地址

题目

地址

https://leetcode.com/problems/snake-in-matrix/description/

内容

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
Explanation:
在这里插入图片描述

Example 2:

Input: n = 3, commands = [“DOWN”,“RIGHT”,“UP”]
Output: 1
Explanation:
在这里插入图片描述

Constraints:

  • 2 <= n <= 10
  • 1 <= commands.length <= 100
  • commands consists only of “UP”, “RIGHT”, “DOWN”, and “LEFT”.
  • The input is generated such the snake will not move outside of the boundaries.

解题

这题就是贪吃蛇操作类问题。以左上角为起始点,根据输入的方向,计算最终落到哪个点上。这题没有太多技巧性,只要把操作翻译成相关运算即可。

#include <string>
#include <vector>
using namespace std;class Solution {
public:int finalPositionOfSnake(int n, vector<string>& commands) {int result = 0;for (string& command : commands) {if (command == "LEFT") {result -= 1;} else if (command == "RIGHT") {result += 1;} else if (command == "DOWN") {result += n;} else if (command == "UP") {result -= n;}}return result;}
};

在这里插入图片描述

代码地址

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com