1020. 飞地的数量
给你一个大小为 m x n 的二进制矩阵 grid ,其中 0 表示一个海洋单元格、1 表示一个陆地单元格。
一次 移动 是指从一个陆地单元格走到另一个相邻(上、下、左、右)的陆地单元格或跨过 grid 的边界。
返回网格中 无法 在任意次数的移动中离开网格边界的陆地单元格的数量。
示例 1:
输入:grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
输出:3
解释:有三个 1 被 0 包围。一个 1 没有被包围,因为它在边界上。
示例 2:
输入:grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
输出:0
解释:所有 1 都在边界上或可以到达边界。
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j] 的值为 0 或 1
广度优先搜索
class Solution: def numEnclaves(self, grid: List[List[int]]) -> int: if not grid: return 0 l1, l2 = len(grid), len(grid[0]) queue, records = list(), list() for i in range(l1): if grid[i][0] == 1: queue.append([i, 0]) if grid[i][l2 - 1]: queue.append([i, l2-1]) for j in range(l2): if grid[0][j] == 1: queue.append([0, j]) if grid[l1 - 1][j] == 1: queue.append([l1 - 1, j]) directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] while queue: num = queue.pop(0) x, y = num[0], num[1] if num not in records: records.append(num) else: continue for direction in directions: _x, _y = x + direction[0], y + direction[1] if 0 <= _x < l1 and 0 <= _y < l2: if (grid[_x][_y] == 1): if ([_x, _y] not in records): queue.append([_x, _y]) count = 0 # 取到所有为1的数量 for i in range(l1): for j in range(l2): if (grid[i][j] == 1 and [i, j] not in records): count += 1 return count
深度优先搜索
class Solution: def numEnclaves(self, grid: List[List[int]]) -> int: if not grid: return 0 l1, l2 = len(grid), len(grid[0]) visit = [[False] * l2 for _ in range(l1)] def dfs(x, y): if x < 0 or x >= l1 or y < 0 or y >= l2 or not grid[x][y] or visit[x][y]: return visit[x][y] = True directions = [[0,1],[0,-1], [1,0],[-1, 0]] for direction in directions: _x, _y = x + direction[0], y + direction[1] if 0 <= _x < l1 and 0 <= _y < l2: if grid[_x][_y]: dfs(_x, _y) for i in range(l1): if grid[i][0]: dfs(i, 0) if grid[i][l2 - 1]: dfs(i, l2 - 1) for j in range(l2): if grid[0][j]: dfs(0, j) if grid[l1 - 1][j]: dfs(l1 - 1, j) count = 0 for i in range(l1): for j in range(l2): if grid[i][j] and not visit[i][j]: count += 1 return count