机器人的运动范围

题目:在地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标数位之和大于k的格子。例如,当K为18时,机器人能进入方格(35,37),因为3+5+3+7=18。但它不能进入方格(35,38),因为3+5+3+8=19.请问该机器人能够到达多少个格子?
分析:
机器人从坐标(0,0)开始移动。当它准备进入坐标(i,j)的格子时,通过检查坐标的位数和来判断机器人是否能够进入。如果能够进入坐标为(i,j)的格子,我们接着再判断它是否进入四个相邻的格子(i,j-1),(i-1,j),(i,j+1),(i+1,j)。因此我们可以用如下的代码来实现回溯法:
 1 int movingCount(int threshold,int rows,int cols)
 2 {
 3  bool *visited= new bool[rows*cols];
 4  for(int i=0;i<rows*cols;++i)
 5      visited[i]=false;
 6  int count=movingCountCore(threshold,rows,cols,0,0,visited);
 7 delete[] visited;
 8 
 9 return count;
10 }
11 
12 int movingCountCore(int threshold,int rows,int cols,int row,int col,bool *visited)
13 {
14  int count=0;
15  if(check(threshold,rows,cols,row,col,visited))
16  {
17   visited[row*cols+col]=true;
18   count=1+movingCountCore(threhold,rows,cols,row-1,col,visited)+
19               movingCountCore(threhold,rows,cols,row,col-1,visited)+
20               movingCountCore(threhold,rows,cols,row+1,col,visited)+
21               movingCountCore(threhold,rows,cols,row,col+1,visited);
22    }
23 return count;
24 }
25 
26 //下面的函数check判断机器人是否进入坐标为(row,col)的方格,而函数getDigitSum
27 //用来得到一个数字的位数之和:
28 bool check(int threshold,int  rows,int cols,int row,int col,bool *visited)
29 {
30  if(row>=0&&row<rows&&col>=0&&col<cols
31      &&getDigitSum(row)+getDigitSum(col)<=threshold
32      &&!visited[row*cols+col])
33  return true;
34 
35  return false;
36 }
37 
38 int getDigitSum(int number)
39 {
40  int sum=0;
41 while(number>0)
42 {
43  sum +=number%10;
44  number /=10;
45 }
46 return sum;
47 }
 
 
原文地址:https://www.cnblogs.com/wxdjss/p/5477971.html