1.题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
2.算法描述
方法:BFS
1.
初
始
化
一
个
与
方
格
同
等
大
小
的
数
组
f
l
a
g
,
用
来
标
识
机
器
人
是
否
可
以
活
动
到
此
,
初
始
时
f
l
a
g
为
全
0
。
1.初始化一个\red{与方格同等大小的数组flag},用来标识机器人是否可以活动到此,初始时flag为全0。
1.初始化一个与方格同等大小的数组flag,用来标识机器人是否可以活动到此,初始时flag为全0。
2.
机
器
人
从
方
格
左
上
角
,
i
,
j
为
0
,
位
置
开
始
递
归
调
用
2.机器人从方格左上角,\red{i,j为0},位置开始递归调用
2.机器人从方格左上角,i,j为0,位置开始递归调用
如
果
i
,
j
位
置
不
合
理
,
或
这
个
位
置
已
经
探
索
过
,
或
这
个
位
置
不
满
足
t
h
r
e
s
h
o
l
d
要
求
,
则
返
回
0
。
\red{\ \ \ \ 如果i,j位置不合理,或这个位置已经探索过,或这个位置不满足threshold要求,则返回0。}
如果i,j位置不合理,或这个位置已经探索过,或这个位置不满足threshold要求,则返回0。
否
则
,
把
这
个
位
置
的
f
l
a
g
标
识
为
1
,
表
示
这
个
位
置
探
索
过
和
机
器
人
可
以
到
达
,
以
后
不
能
重
复
探
索
。
\red{\ \ \ \ 否则,把这个位置的flag标识为1,表示这个位置探索过和机器人可以到达,以后不能重复探索。}
否则,把这个位置的flag标识为1,表示这个位置探索过和机器人可以到达,以后不能重复探索。
以
这
个
位
置
为
起
始
点
,
递
归
地
探
索
上
、
下
、
左
、
右
四
个
方
向
的
可
运
动
范
围
,
返
回
四
个
运
动
范
围
的
数
量
+
1
。
\red{\ \ \ \ 以这个位置为起始点,递归地探索上、下、左、右四个方向的可运动范围,返回四个运动范围的数量+1。}
以这个位置为起始点,递归地探索上、下、左、右四个方向的可运动范围,返回四个运动范围的数量+1。
3.代码描述
3.1.Java代码
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
int[][] flag = new int[rows][cols];//用来标识位置机器人是否可以到此位置
return helper(0, 0, rows, cols, flag, threshold);
}
private int helper(int i, int j, int rows, int cols, int[][] flag, int threshold){
//位置不合理 位置已经被探索 位置不满足要求 返回0
if(i<0||i>=rows||j<0||j>=cols||flag[i][j]==1||sum(i,j)>threshold) return 0;
//位置合理 满足要求
flag[i][j] = 1;
//返回1 + 从这个位置上、下、左、右探索的可行位置
return helper(i+1, j, rows, cols, flag, threshold)+
helper(i-1, j, rows, cols, flag, threshold)+
helper(i, j+1, rows, cols, flag, threshold)+
helper(i, j-1, rows, cols, flag, threshold)+1;
}
private int sum(int i, int j){
int ans = 0;
while(i!=0){
ans += i % 10;
i /= 10;
}
while(j!=0){
ans += j % 10;
j /= 10;
}
return ans;
}
}
3.2.Python代码
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
flag = [[0 for j in range(cols)] for i in range(rows)]
return self.helper(0, 0, rows, cols, flag, threshold)
def helper(self, i, j, rows, cols, flag, threshold):
if i<0 or i>=rows or j<0 or j>=cols or flag[i][j]==1 or self.fun(i,j)>threshold:
return 0
flag[i][j] = 1
return (self.helper(i-1, j, rows, cols, flag, threshold) +
self.helper(i+1, j, rows, cols, flag, threshold) +
self.helper(i, j-1, rows, cols, flag, threshold) +
self.helper(i, j+1, rows, cols, flag, threshold)+1)
def fun(self, i, j):
ans = 0
while i:
ans += i % 10
i //= 10
while j:
ans += j % 10
j //= 10
return ans