面试题13. 机器人的运动范围

题目:

地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?

示例 1:

输入:m = 2, n = 3, k = 1
输出:3

示例 2:

输入:m = 3, n = 1, k = 0
输出:1

提示:

\(1 <= n,m <= 100\)
\(0 <= k <= 20\)

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


class Solution {
public:
    int dx[4] = {1,-1,0,0}, dy[4] = {0,0,-1,1};
    typedef pair<int,int> PII;
    int get_sum(PII p)
    {
        int s = 0;
        while(p.first)
        {
            s += p.first % 10;
            p.first /= 10;
        }
        while(p.second)
        {
            s += p.second % 10;
            p.second /= 10;
        }
        return s;
    }


    int movingCount(int m, int n, int k) {
        if(!m || !n) return 0;//特判
        queue<PII> q;
        vector<vector<bool>> st(m,vector<bool>(n,false));//定义一个二维数组st表示是否有是否有走过
        int res = 0;//定义答案
        q.push({0,0});//首先我们先把起点放入栈中
        while(q.size())
        {
            auto t = q.front();
            q.pop();

            //遍历过或者说不满足条件则直接跳过
            if(st[t.first][t.second] || get_sum(t) > k) continue;
            res++;
            st[t.first][t.second] = true;
            for(int i = 0; i < 4; i ++)
            {
                int x = t.first + dx[i], y = t.second + dy[i];
                if(x >= 0 && x < m && y >= 0 && y < n) q.push({x,y});

            }
        }
        return res;
    }   
};
posted @ 2022-09-13 17:04  Sheldon2  阅读(38)  评论(0)    收藏  举报