卡码网 99 岛屿数量
深搜版:
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
def main():
n, m = map(int, input().split())
grid = []
res = 0
for i in range(n):
grid.append(list(map(int, input().split())))
visited = [[False] * m for _ in range(n)]
for i in range(n):
for j in range(m):
if grid[i][j] == 1 and not visited[i][j]:
res += 1
dfs(grid, visited, i, j)
print(res)
def dfs(grid, visited, i, j):
if visited[i][j] or grid[i][j] == 0:
return
visited[i][j] = True
for x, y in direction:
next_x = i + x
next_y = j + y
if next_x < 0 or next_x >= len(grid) or next_y < 0 or next_y >= len(grid[0]):
continue
dfs(grid, visited, next_x, next_y)
if __name__ == '__main__':
main()
广搜版:
from collections import deque
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
def main():
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)]
res = 0
for i in range(n):
for j in range(m):
if not visited[i][j] and grid[i][j] == 1:
res += 1
bfs(grid, visited, i, j)
print(res)
def bfs(grid, visited, x, y):
que = deque([])
que.append([x, y])
visited[x][y] = True
while que:
cur_x, cur_y = que.popleft()
for i, j in directions:
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])
if __name__ == '__main__':
main()
卡码网 100 岛屿的最大面积
学习全局变量的使用
from collections import deque
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
count = 0
def bfs(grid, visited, x, y):
global count
que = deque()
que.append([x, y])
while que:
cur_x, cur_y = que.popleft()
for i, j in directions:
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 grid[next_x][next_y] == 1 and not visited[next_x][next_y]:
count += 1
visited[next_x][next_y] = True
que.append([next_x, next_y])
def main():
global count
n, m = map(int, input().split())
grid = []
for _ in range(n):
grid.append(list(map(int, input().split())))
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]:
count = 1
visited[i][j] = True
bfs(grid, visited, i, j)
res = max(count, res)
print(res)
if __name__ == '__main__':
main()