学习资料:https://www.programmercarl.com/kamacoder/0099.岛屿的数量深搜.html#思路
深度优先搜索和广度优先搜索
今天用的邻接矩阵
学习记录:
卡码网99.岛屿数量 (深搜or广搜;用一个自己设计的二维矩阵来控制节点的移动方向:上下左右)
点击查看代码
from collections import deque
direction = [[1,0], [0,1], [-1,0], [0, -1]] # 上,右,下,左
def bfs(visited, grid, x, y):
"""广搜"""
que = deque([])
que.append([x, y])
while que:
cur_x, cur_y = que.popleft()
for i, j in direction:
next_x = cur_x + i
next_y = cur_y + j
if next_x<0 or next_x>=len(grid) or next_y<0 or next_y>=len(grid[0]):
continue
if not visited[next_x][next_y] and grid[next_x][next_y] == 1:
visited[next_x][next_y] = True
que.append([next_x, next_y])
def dfs(visited, grid, x, y):
"""深搜"""
for i, j in direction:
next_x = x+i
next_y = y + j
# 下标越界,跳过 (这一小片区域的边界)
if next_x<0 or next_x>=len(grid) or next_y<0 or next_y>=len(grid[0]):
continue
# 遇到为访问的陆地,标记并使用深搜
if not visited[next_x][next_y] and grid[next_x][next_y]==1:
visited[next_x][next_y] = True
dfs(visited, grid, next_x, next_y)
if __name__ == "__main__":
n, m = map(int, input().split())
# 构造邻接矩阵
grid = []
for i in range(n):
grid.append(list(map(int, input().split())))
# 构造访问表,若以访问则为True
visited = [[False]*m for _ in range(n)]
# 岛屿数量
res = 0
for i in range(n):
for j in range(m):
# 如果当前是陆地,且未被访问过,说明找到了一片新的陆地,标记该访问情况,深搜找这片的范围
if grid[i][j] == 1 and not visited[i][j]:
res += 1
visited[i][j] = True
bfs(visited, grid, i, j) # dfs(visited, grid, i, j) 也可以
print(res)
卡码网100.岛屿的最大面积(深搜法;给前面这道题的基础上,遍历每片岛屿时,要记录每个陆地值得到岛屿面积)
点击查看代码
directions = [[1,0],[0,1],[-1,0],[0,-1]]
count = 0
def dfs(visited, grid, x, y):
global count # 设置全局变量
for i,j in directions:
cur_x = x + i
cur_y = y + j
if cur_x<0 or cur_x>=len(grid) or cur_y<0 or cur_y>=len(grid[0]):
continue
if not visited[cur_x][cur_y] and grid[cur_x][cur_y]==1:
visited[cur_x][cur_y] = True
count += 1
dfs(visited, grid, cur_x, cur_y)
n, m = map(int, input().split())
grid = []
for i in range(n):
grid.append(list(map(int, input().split())))
visited = [[False]*m for _ in range(n)]
result = 0 # 记录count的最大值
for i in range(n):
for j in range(m):
if grid[i][j]==1 and not visited[i][j]:
count = 1
visited[i][j] = True
dfs(visited, grid, i, j)
result = max(result, count)
print(result)
PS:不想学习的一天,想念卡哥视频的一天,啥时候出图论啊
学的比较潦草,多复习
好冷,今天吃了好多美食,豆花牛肉、大盘鸡、凉皮、羊肉抓饭、冰淇淋,嗝~
让我们一起倒数十个数!