剑指offer之 机器人的运动范围

题目描述

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

思路

从(0,0)开始走,每成功走一步标记当前位置为true,然后从当前位置往四个方向探索。探索时,判断当前节点是否可达的标准为:
1)当前节点在矩阵内;
2)当前节点未被访问过;
3)当前节点满足limit限制。
若可达,则标记对应的flag为true,count++

代码

class Solution {
public:
    int count= 0;
    int movingCount(int threshold, int rows, int cols)
    {
        if(threshold < 1 || rows < 1 || cols <1)
            return 0;
        bool *flag=new bool[rows*cols];
        memset(flag,false,rows*cols);
        move_on(threshold,rows,cols,0,0,flag);
        return count;
    }
    void move_on(int threshold, int rows, int cols, int P_x, int P_y, bool* flag)
    {
        int index = P_x * cols + P_y;
        int condition = cal(P_x,P_y);
        if(P_x < 0 || P_x > rows-1 || P_y < 0 || P_y > cols-1 || condition > threshold || flag[index] == true)
            return;
        flag[index] = true;
        count++;
        move_on(threshold,rows,cols,P_x+1,P_y,flag);
        move_on(threshold,rows,cols,P_x,P_y+1,flag);
        move_on(threshold,rows,cols,P_x-1,P_y,flag);
        move_on(threshold,rows,cols,P_x,P_y-1,flag);
        return;
    }
    int cal(int x, int y)
    {
        int res = 0;
        string s_x,s_y,s;
        s_x = to_string(x);
        s_y = to_string(y);
        s = s_x + s_y;
        for(int i = 0; i < s.size();i++)
        {
            res = res + s[i]-'0';
        }
        return res;
    }
};
发布了85 篇原创文章 · 获赞 0 · 访问量 389

猜你喜欢

转载自blog.csdn.net/weixin_38312163/article/details/104888089