【题目描述】
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
【解题思路】
此题有两种实现方式,一种是dfs递归求解,一种是直接遍历,直接遍历的方法较为简单,所以这里阐述用dfs递归求解的方法,由于是从坐标0,0的结点开始遍历的,所以只要往右和往下遍历就行,所有的结点就都可以遍历得到,再用一个visited数组来记录是否已经访问过该位置即可。用Python实现的代码如下:
# -*- coding:utf-8 -*-
class Solution:
def dfs(self, x, y, threshold, rows, cols):
if x>=rows or x<0 or y>=cols or y<0 or visited[x][y] or self.count(x)+self.count(y)>threshold:
return False
visited[x][y] = 1
return self.dfs(x+1, y, threshold, rows, cols) + self.dfs(x, y+1, threshold, rows, cols) + 1
def count(self, num):
res = 0
while num:
res += num%10
num /= 10
return res
def movingCount(self, threshold, rows, cols):
# write code here
global visited
visited = [[0 for j in range(cols)] for i in range(rows)]
return self.dfs(0, 0, threshold, rows, cols)