题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
DFS实现,不需要回溯,找到所有的能够走的点,并不是一条路径上面的点
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
vis = [[0 for y in range(cols)] for x in range(rows)]
return self.DFS(0, 0, rows, cols, vis, threshold)
def DFS(self, x, y, rows, cols, vis, threshold):
if x >= 0 and x < rows and y >= 0 and y < cols and vis[x][y] == 0 and \
self.Judge(x, y, threshold) == True:
vis[x][y] = 1
return self.DFS(x - 1, y, rows, cols, vis, threshold) + \
self.DFS(x + 1, y, rows, cols, vis, threshold) + \
self.DFS(x, y - 1, rows, cols, vis, threshold) + \
self.DFS(x, y + 1, rows, cols, vis, threshold) + 1
return 0
def Judge(self, x, y, threshold):
n = sum([int(i) for i in str(x)]) + sum([int(i) for i in str(y)])
if n > threshold:
return False
return True
if __name__ == "__main__":
a = Solution()
print a.movingCount(8, 5, 5) # 25
print a.movingCount(15, 20, 20) # 359
使用内部类来实现
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
u"内部类实现"
# write code here
vis = [[0 for y in range(cols)] for x in range(rows)]
def DFS(x, y):
if x >= 0 and x < rows and y >= 0 and y < cols and vis[x][y] == 0 \
and sum(map(int, str(x) + str(y))) <= threshold: # 使用map把字符串转化为list
vis[x][y] = 1
# 四个方向进行求和,每执行一次接下来的 return 说明有一个点满足条件,对应加 1
return DFS(x - 1, y) + DFS(x + 1, y) + DFS(x, y - 1) + DFS(x, y + 1) + 1
return 0
return DFS(0, 0)
if __name__ == "__main__":
a = Solution()
print a.movingCount(8, 5, 5) # 25
print a.movingCount(15, 20, 20) # 359