/*
题目:
地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始运动,
每次可向上、下、左、右移动一格,但不能进入行坐标和列坐标之和大于k的格子。
如,当k=18时,机器人能进入(35,37),因为3+5+3+7=18。
但不能进入(35,38),问机器人能够到达多少格子。
*/
/*
思路:
递归法。
机器人从第一个格子走;
计算机器人向左、右、上、下可走的格子数之和。
使用visited进行标注,防止已走过的格子被重复计数。
*/
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
bool isValid(int row,int col,int threshold){
int num = 0;
while(row != 0){
num += row % 10;
row = row / 10;
}
while(col != 0){
num += col % 10;
col = col / 10;
}
return num > threshold ? false : true;
}
int movingCounCore(int row,int col,int rows,int cols,int threshold,bool* visited){
int myCount = 0;
//cout<<row<<" "<<col<<endl;
if(row >= 0 && col >=0 && row < rows && col < cols && !visited[cols*row+col] && isValid(row,col,threshold)){
visited[row*cols + col] = true;
myCount = 1+movingCounCore(row+1,col,rows,cols,threshold,visited) + movingCounCore(row,col+1,rows,cols,threshold,visited) +
movingCounCore(row-1,col,rows,cols,threshold,visited) + movingCounCore(row,col-1,rows,cols,threshold,visited);
}
return myCount;
}
int movingCount(int threshold,int rows,int cols){
if(threshold < 0 || rows <= 0 || cols <= 0){
return 0;
}
bool *visited = new bool[rows*cols];
memset(visited,false,rows*cols);
int myCount = movingCounCore(0,0,rows,cols,threshold,visited);
delete[] visited;
return myCount;
}
int main(){
cout<<movingCount(5,2,2)<<endl;
}