【66】机器人的运动范围
时间限制:1秒空间限制:32768K回溯法
题目描述 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动, 每一次只能向左,右,上,下四个方向移动一格, 但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。 但是,它不能进入方格(35,38),因为3+5+3+8 = 19。 请问该机器人能够达到多少个格子? 牛客网题目链接点击这里
VS2010代码:
#include<iostream>
using namespace std;
class Solution {
/********位和控制函数函数****************/
bool SumOfBit(
int threshold1,
int curRow,
int curCol)
{
int SumBit=
0;
while(curRow)
{
SumBit=SumBit+curRow%
10;
curRow=curRow/
10;
}
while(curCol)
{
SumBit=SumBit+curCol%
10;
curCol=curCol/
10;
}
return SumBit>threshold1?
0:
1;
}
/**********路径寻找函数**********/
void FindPath(
int threshold1,
int rows1,
int cols1,
int curRow,
int curCol,
int* flag)
{
if(curRow<
0 || curCol<
0 || curRow>rows1-
1 || curCol>cols1-
1)
return;
if(!SumOfBit(threshold1,curRow,curCol) )
return;
if(flag[curRow*cols1+curCol]==
1)
return;
flag[curRow*cols1+curCol]=
1;
FindPath( threshold1,rows1,cols1, curRow-
1, curCol, flag);
FindPath( threshold1,rows1,cols1, curRow, curCol+
1, flag);
FindPath( threshold1,rows1,cols1, curRow+
1, curCol, flag);
FindPath( threshold1,rows1,cols1, curRow, curCol-
1, flag);
}
public:
int movingCount(
int threshold,
int rows,
int cols)
{
if(threshold<
0 || rows<
1 || cols<
1)
return 0;
int* Flag=
new int[rows*cols];
for(
int i=
0; i<rows*cols; i++)
Flag[i]=
0;
FindPath( threshold,rows,cols,
0,
0, Flag);
int reachedNum=
0;
for(
int i=
0; i<rows*cols; i++)
{
if(Flag[i]==
1)
reachedNum++;
}
return reachedNum;
}
};
int main()
{
Solution s1;
cout<<s1.movingCount(
5,
4,
4)<<endl;
}
牛客网通关图片:
另附(剑指offer)66道通关卡片:
转载请注明原文地址: https://ju.6miu.com/read-1300388.html