题解 | #机器人的运动范围#
机器人的运动范围
http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
class Solution:
def movingCount(self, threshold: int, rows: int, cols: int) -> int:
# write code here
'''
1.创建rows行cols列的全零矩阵
2.calc_thre()函数,str int 实现题目条件
3.count()函数,计数获取矩阵内1的个数
4.dfs()函数,not vis[x][y]是指该坐标为0,经过坐标设为1,for循环遍历路径,返回count()函数
注:机器人可以选择返回经过的路径,用dfs的话需要让它遍历所有的路径,也就是加上for循环
'''
vis = [[0] * cols for _ in range(rows)]
def calc_thre(x, y):
ans = 0
for i in str(x):
ans += int(i)
for i in str(y):
ans += int(i)
return ans <= threshold
def count():
num = 0
for i in range(rows):
for j in range(cols):
if vis[i][j] == 1:
num += 1
return num
def dfs(x, y):
if 0 <= x < rows and 0 <= y < cols and not vis[x][y] and calc_thre(x, y):
vis[x][y] = 1
for i in range(4):
dfs(x, y + 1) or dfs(x, y - 1) or dfs(x + 1, y) or dfs(x - 1, y)
return count()
return 0
return dfs(0, 0)
def movingCount(self, threshold: int, rows: int, cols: int) -> int:
# write code here
'''
1.创建rows行cols列的全零矩阵
2.calc_thre()函数,str int 实现题目条件
3.count()函数,计数获取矩阵内1的个数
4.dfs()函数,not vis[x][y]是指该坐标为0,经过坐标设为1,for循环遍历路径,返回count()函数
注:机器人可以选择返回经过的路径,用dfs的话需要让它遍历所有的路径,也就是加上for循环
'''
vis = [[0] * cols for _ in range(rows)]
def calc_thre(x, y):
ans = 0
for i in str(x):
ans += int(i)
for i in str(y):
ans += int(i)
return ans <= threshold
def count():
num = 0
for i in range(rows):
for j in range(cols):
if vis[i][j] == 1:
num += 1
return num
def dfs(x, y):
if 0 <= x < rows and 0 <= y < cols and not vis[x][y] and calc_thre(x, y):
vis[x][y] = 1
for i in range(4):
dfs(x, y + 1) or dfs(x, y - 1) or dfs(x + 1, y) or dfs(x - 1, y)
return count()
return 0
return dfs(0, 0)