思路:将地图全部置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)
本文介绍了一种使用深度优先搜索(DFS)算法解决网格问题的方法,如计算岛屿数量或最大岛屿面积。通过将地图初始化为全1状态,然后遍历可达点,将这些点标记为0并增加计数,可以有效地找到所有独立的区域。这种方法适用于LeetCode等平台上的相关问题。
942

被折叠的 条评论
为什么被折叠?



