剣指offer全集python版-ロボットの動き範囲

11074 ワード

地面にm行とn列の四角形がある.1つのロボットは座標0,0の格子から移動し始め、毎回左、右、上、下の4つの方向に1格しか移動できませんが、行座標と列座標の数位の和がkより大きい格子に入ることはできません.例えば、kが18である場合、3+5+3+7=18であるため、ロボットは格子(35,37)に入ることができる.しかし,3+5+3+8=19のため,格子(35,38)に入ることはできなかった.すみません、このロボットは何個の格子に達することができますか?
考え方:
遡及して、アクセスするかどうかを記録します.
コード:
# -*- coding:utf-8 -*-
class Solution:
    def movingCount(self, threshold, rows, cols):
        # write code here
        flag = []
        for i in range(rows):
            flag.append([0] * cols)
        def DFS(start, rows, cols):
            if flag[start[0]][start[1]] != 1:
                if self.sumNumber(start[0], start[1])<= threshold:
                    flag[start[0]][start[1]] = 1
                    if start[0]+1<rows :
                        DFS([start[0]+1, start[1]], rows, cols)
                    if start[0]-1>=0 :
                        DFS([start[0]-1, start[1]], rows, cols)
                    if start[1]+1 < cols:
                        DFS([start[0], start[1]+1], rows, cols)
                    if start[1]-1>=0:
                        DFS([start[0], start[1]-1], rows, cols)
                else:
                    flag[start[0]][start[1]] = -1
        DFS([0,0], rows, cols)
        count = 0
        for i in range(rows):
            for j in range(cols):
                if flag[i][j] == 1:
                    count += 1
        return count
    def sumNumber(self, rows, cols):
        r = str(rows)
        c = str(cols)
        count = 0
        for i in r:
            count += int(i)
        for j in c:
            count += int(j)
        print(count)
        return count