题目:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
class Solution {
//其实这个里面隐含了不能够重复走的条件,如果能重复走,那就是无限个了呀,因此定义一个数组用于判断是否走过。
//要求坐标各位之和相加小于threshold则需要定义各位一个函数用来判断是否大于threshold
//注意边界判断
//注意异常输入
//总和等于上+下+左边+ 右边 +1(当前的格子也要算上哟)
public:
int sumOfIdx(int n){
int sum =0;
while(n>0) {
sum += n % 10;
n = n / 10;
}
return sum;
}
int getMovingCount(int threshold, int rows, int cols, int row, int col, bool *array) {
int count =0;
bool check = ((sumOfIdx(row) + sumOfIdx(col)) <= threshold);
check = check&&(row<rows)&&(row>=0)&&(col<cols)&&(col>=0);
check = check&&(!array[row*cols+col]); //没有被访问过
if(check){
array[row*cols+col] = true;
count =1 + getMovingCount(threshold, rows, cols, row-1, col, array) // 上
+ getMovingCount(threshold, rows, cols, row+1, col, array) // 下
+ getMovingCount(threshold, rows, cols, row, col-1, array) // 左
+ getMovingCount(threshold, rows, cols, row, col+1, array);// 右
}
return count;
}
int movingCount(int threshold, int rows, int cols)
{
if(rows <=0 || cols<= 0 || threshold <= 0) return 0;
//首先定义一个数组用于判定当前位置是否走过
bool *array = new bool[rows * cols];
for(int i = 0; i < rows * cols; i++)
array[i] = false;
int count = getMovingCount(threshold, rows, cols, 0, 0, array);
delete[] array;
return count;
}
};
这个是快手上面的题目,提交了一下,还是发现上面写的有问题,上面我判断threshold<=0 就返回为0是有问题的,因为机器完全可以只在0.0处运动所以应该改成 threshold< 0 就返回为0
#include <bits/stdc++.h>
using namespace std;
//其实这个里面隐含了不能够重复走的条件,如果能重复走,那就是无限个了呀,因此定义一个数组用于判断是否走过。
//要求坐标各位之和相加小于threshold则需要定义各位一个函数用来判断是否大于threshold
//注意边界判断
//注意异常输入
//总和等于上+下+左边+ 右边 +1(当前的格子也要算上哟)
int sumOfIdx(int n){
int sum =0;
while(n>0) {
sum += n % 10;
n = n / 10;
}
return sum;
}
int getMovingCount(int threshold, int rows, int cols, int row, int col, bool *array) {
int count =0;
bool check = ((sumOfIdx(row) + sumOfIdx(col)) <= threshold);
check = check&&(row<rows)&&(row>=0)&&(col<cols)&&(col>=0);
check = check&&(!array[row*cols+col]); //没有被访问过
if(check){
array[row*cols+col] = true;
count =1 + getMovingCount(threshold, rows, cols, row-1, col, array) // 上
+ getMovingCount(threshold, rows, cols, row+1, col, array) // 下
+ getMovingCount(threshold, rows, cols, row, col-1, array) // 左
+ getMovingCount(threshold, rows, cols, row, col+1, array);// 右
}
return count;
}
int movingCount(int threshold, int rows, int cols)
{
if(rows <=0 || cols<= 0 || threshold < 0) return 0;
//首先定义一个数组用于判定当前位置是否走过
bool *array = new bool[rows * cols];
for(int i = 0; i < rows * cols; i++)
array[i] = false;
int count = getMovingCount(threshold, rows, cols, 0, 0, array);
delete[] array;
return count;
}
int main(){
int threshold =0;
int rows = 0;
int cols = 0;
cin>> rows >> cols >> threshold;
int count = movingCount(threshold, rows, cols);
cout<<count;
return 0;
}