题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思想:类似"矩阵中的路径",看成寻找"11111111111"的字符串,最大的长度。
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
mat = [[None for j in range(cols)] for i in range(rows)]
for i in range(rows):
for j in range(cols):
temp = list(str(i)) + list(str(j))
mat[i][j] = 1 if sum([int(t) for t in temp]) <= threshold else 0
print mat
res = float('-inf')
for i in range(rows):
for j in range(cols):
flag = [[False for p in range(cols)] for q in range(rows)]
index = [0,0]
self.find(mat,flag,0,rows-1,0,cols-1,index,i,j)
res = max(res,index[1])
return res
def find(self,mat,flag,r1,r2,c1,c2,index,i,j):
if i < r1 or i > r2 or j < c1 or j > c2:
return False
res = False
if mat[i][j] == 1 and flag[i][j] == False:
index[0] += 1
flag[i][j] = True
if index[0] > index[1]:
index[1] = index[0]
res = self.find(mat,flag,r1,r2,c1,c2,index,i+1,j) \
or self.find(mat,flag,r1,r2,c1,c2,index,i-1,j) \
or self.find(mat, flag, r1, r2, c1, c2, index, i, j+1) \
or self.find(mat, flag, r1, r2, c1, c2, index, i, j-1)
#回溯
if res == False:
index[0] -= 1
flag[i][j] = False
return res
if __name__ == "__main__":
so = Solution()
res = so.movingCount(1,3,3)
print(res)
网友评论