美文网首页
2019-08-20 剑指 机器人的运动范围

2019-08-20 剑指 机器人的运动范围

作者: mztkenan | 来源:发表于2019-08-20 19:48 被阅读0次

37min,痛苦地调了半天,发现是=写成了==号。一次通过

class Solution:
    def __init__(self):
        self.cnt=0

    def movingCount(self, threshold, rows, cols):
        matrix=[[i+j*cols for i in range(cols)]for j in range(rows)]
        self.dfs(threshold,rows,classmethod,0,0,matrix)
        return self.cnt


    def dfs(self,threshold,rows,cols,i,j,matrix):
        if self.check_valid(threshold,rows,cols,i,j,matrix):
            self.cnt+=1
            matrix[i][j]=None   # 痛苦地调了半天,发现是=写成了==号
            print(matrix)
            self.dfs(threshold,rows,cols,i,j+1,matrix)
            self.dfs(threshold,rows,cols,i,j-1,matrix)
            self.dfs(threshold,rows,cols,i-1,j,matrix)
            self.dfs(threshold,rows,cols,i+1,j,matrix)

    def check_valid(self,threshold,rows,cols,i,j,matrix):
        try:
            if matrix[i][j]!=None and self.get_digit_sum(i,j)<=threshold:return True
            else:return False
        except:  # 这种情况是数组越界,用try catch写起来很简单
            return False

    def get_digit_sum(self,i,j):
        return reduce(lambda x,y:x+y,map(lambda x:int(x),str(i)+str(j))) # 求数位和一行搞定爽不爽

if __name__ == '__main__':
    t=Solution()
    print(t.get_digit_sum(1,3))
    print(t.check_valid(18,100,100,35,37,[[1 for i in range(100)] for j in range(100)]))
    print(t.movingCount(3,3,6))

相关文章

网友评论

      本文标题:2019-08-20 剑指 机器人的运动范围

      本文链接:https://www.haomeiwen.com/subject/uejmsctx.html