岛屿数量 深搜
def dfs(x, y, graph):
if x<0 or x>=len(graph) or y<0 or y>=len(graph[0]) or graph[x][y]==0:
return
graph[x][y]=0
dfs(x+1, y, graph)
dfs(x-1, y, graph)
dfs(x, y+1, graph)
dfs(x, y-1, graph)
if __name__=='__main__':
r,l =map(int,input().split(' '))
graph = []
for i in range(r):
row = list(map(int,input().split(' ')))
graph.append(row)
result = 0
for i in range(r):
for j in range(l):
if graph[i][j]==1:
dfs(i,j,graph)
result+=1
print(result)
岛屿数量 广搜
from collections import deque
def bfs(x, y, graph):
graph[x][y]=0
que = deque([[x,y]])
while que:
x, y = que.popleft()
directions = [[0,1],[0,-1],[1,0],[-1,0]]
for k in range(4):
x0, y0 = directions[k]
new_x = x+x0
new_y = y+y0
if new_x>=0 and new_x<len(graph) and new_y>=0 and new_y<len(graph[0]) and graph[new_x][new_y]==1:
que.append([new_x, new_y])
graph[new_x][new_y]=0
return
if __name__=='__main__':
r,l =map(int,input().split(' '))
graph = []
for i in range(r):
row = list(map(int,input().split(' ')))
graph.append(row)
result = 0
for i in range(r):
for j in range(l):
if graph[i][j]==1:
bfs(i,j,graph)
result+=1
print(result)
岛屿的最大面积
from collections import deque
def bfs(x, y, graph):
s=1
graph[x][y]=0
que = deque([[x,y]])
while que:
x, y = que.popleft()
directions = [[0,1],[0,-1],[1,0],[-1,0]]
for k in range(4):
x0, y0 = directions[k]
new_x = x+x0
new_y = y+y0
if new_x>=0 and new_x<len(graph) and new_y>=0 and new_y<len(graph[0]) and graph[new_x][new_y]==1:
que.append([new_x, new_y])
graph[new_x][new_y]=0
s+=1
return s
if __name__=='__main__':
r,l =map(int,input().split(' '))
graph = []
for i in range(r):
row = list(map(int,input().split()))
graph.append(row)
result = 0
for i in range(r):
for j in range(l):
if graph[i][j]==1:
s = bfs(i,j,graph)
result = max(result, s)
print(result)
def dfs(x, y, graph, s):
if x<0 or x>=len(graph) or y<0 or y>=len(graph[0]) or graph[x][y]==0:
return s
graph[x][y]=0
s+=1
s = dfs(x+1, y, graph, s)
s = dfs(x-1, y, graph, s)
s = dfs(x, y+1, graph, s)
s = dfs(x, y-1, graph, s)
return s
if __name__=='__main__':
r,l =map(int,input().split())
graph = []
for i in range(r):
row = list(map(int,input().split()))
graph.append(row)
result = 0
for i in range(r):
for j in range(l):
if graph[i][j]==1:
s = dfs(i,j,graph,0)
result = max(result, s)
print(result)