剑指offer-机器人的运动范围(python)

思路:将地图全部置1,遍历能够到达的点,将遍历的点置0并令计数+1.这个思路在找前后左右相连的点很有用,比如leetcode中的海岛个数问题/最大海岛问题都可以用这种方法来求解。

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.count=0
    def movingCount(self, threshold, rows, cols):
        # write code here
        arr = [[1 for i in range(cols)] for j in range(rows)]
        self.dfs(arr, 0, 0, threshold)
        return self.count
    def dfs(self, arr, i, j, threshold):
        if i < 0 or j < 0 or i >= len(arr) or j >= len(arr[0]):
            return
        l = list(map(int, list(str(i))))
        r = list(map(int, list(str(j))))
        if sum(l) + sum(r) > threshold or arr[i][j] != 1:
            return
        arr[i][j] = 0
        self.count += 1
        self.dfs(arr, i + 1, j, threshold)
        self.dfs(arr, i - 1, j, threshold)
        self.dfs(arr, i, j + 1, threshold)
        self.dfs(arr, i, j - 1, threshold)

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104480212