剑指offer13--机器人的运动范围

题目描述

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

思路:

回溯法:

考虑清楚如何递归,怎么判断条件就好。

class Solution {
public:
    int tran(int a){
        int res=0;
        while(a>0){
            res+=a%10;
            a/=10;
        }
        return res;
    }
    int movingCountCore(int threshold, int rows, int cols,int x,int y,bool** visit){
        int i,j;
        int res=0;
        if(x>=0&&y>=0&&x<rows&&y<cols)
            if(tran(x)+tran(y)<=threshold&&!visit[x][y]){
                visit[x][y]=1;
                res++;
                res+=movingCountCore(threshold,rows,cols,x-1,y,visit);
                res+=movingCountCore(threshold,rows,cols,x+1,y,visit);
                res+=movingCountCore(threshold,rows,cols,x,y+1,visit);
                res+=movingCountCore(threshold,rows,cols,x,y-1,visit);
            }
        return res;
    }
    int movingCount(int threshold, int rows, int cols)
    {
        bool **visit=new bool*[rows];
        for(int i=0;i<rows;i++)
            *(visit+i)=new bool[cols];
        for(int i=0;i<rows;i++)
            for(int j=0;j<cols;j++)
                visit[i][j]=0;
        int res=movingCountCore(threshold,rows,cols,0,0,visit);
        return res;
    }
};


BFS(广度优先搜索):参考牛客网。。。

动态规划:参考牛客网。。。

https://www.nowcoder.com/questionTerminal/6e5207314b5241fb83f2329e89fdecc8

调试代码:

#include <iostream>

using namespace std;

int tran(int a){
	int res=0;
	while(a>0){
		res+=a%10;
		a/=10;
	}
	return res;
}
int movingCountCore(int threshold, int rows, int cols,int x,int y,bool** visit){
	int i,j;
	int res=0;
	if(x>=0&&y>=0&&x<rows&&y<cols)
		if(tran(x)+tran(y)<=threshold&&!visit[x][y]){
			visit[x][y]=1;
			res++;
			res+=movingCountCore(threshold,rows,cols,x-1,y,visit);
			res+=movingCountCore(threshold,rows,cols,x+1,y,visit);
			res+=movingCountCore(threshold,rows,cols,x,y+1,visit);
			res+=movingCountCore(threshold,rows,cols,x,y-1,visit);
		}
	return res;
}

int movingCount(int threshold, int rows, int cols)
{
	bool **visit=new bool*[rows];
	for(int i=0;i<rows;i++)
		*(visit+i)=new bool[cols];
	for(int i=0;i<rows;i++)
		for(int j=0;j<cols;j++)
			visit[i][j]=0;
	//visit[0][0]=1;
	int res=movingCountCore(threshold,rows,cols,0,0,visit);
	return res;
}

int main ()
{
	int res=movingCount(10,1,100);
	cout<<res<<endl;
	return 0;

}

猜你喜欢

转载自blog.csdn.net/m0_37561165/article/details/81240645