机器人能走多少个迷宫

题目:地图上有一个m行n列的方格,一个机器人从坐标(0,0)的格子开始移动,它每一次可以移动的方向是上、下、左、右,且每次只能移动一格,但是不能进入行坐标和列坐标数位之和大于K的格子。例子,当K为16时,机器人能够进入方格(24,19),因为2+4+1+9=16,但是不能进入方格(34,28),因为3+4+2+8=17>16,

问:该机器人能够达到多少个格子。

分析:

这个题目比较简单,可以把问题分解为4个部分:

1)如何计算数字的位数之和

2)机器人是否能够进入某个格子

3) 如果能进入格子,四邻域内的格子是否能够进入,

4)统计一共能够达到多个格子

1)代码

//计算数字位数之和
int getDigitSum(int number)
{

    int sum=0;//临时变量,保存一个数字数位和
    
    while(number){
        
        sum+=number%10;
        number/=10;
    }    

    return sum;

}

2)代码

//机器人能否进入某个格子,即从三个方面考虑:
//①是否越界,②数位之和是否满足条件,③邻域格子是否已经访问过
bool check(int threshold,int rows,int cols,int row,int col,bool* visit){

    if(row>=0&&col>=0&&row<rows&&col<cols&&getDigitSum(row)+getDigitSum(col)<=threshold)
        &&!visit[row*cols+col])
        return true;
    return false;

}

3)代码

int movingCountCore(int threshold,int rows,int cols, int row,int col, bool *visited)
{

    int count=0;
    if(check(threshold,rows,cols,row,col,bool* visited))
        {

            visited[row*cols+col]=true;
            count+=1+movingCountCore(threshold,rows,cols,row-1,col,visited)
                 +movingCountCore(threshold,rows,cols,row+1,col,visited)
                 +movingCountCore(threshold,rows,cols,row,col-1,visited)
                 +movingCountCore(threshold,rows,cols,row,col+1,visited);
        }
    return count;

}

4)代码

int movingCount(int threshold,int rows,int cols)
{
    //要考虑负值的情况
    if(threshold<0||rows<=0||cols<=0)
        {return 0;}
    
    bool* visited=new bool[rows*cols];
    for(int i=0;i<=rows*cols;++i){
        visited=false;
    }
    int count=movingCountCore(threshold,rows,cols,0,0,visited);
    delete[] visited;
    return count;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DLANDML

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值