题目描述
代码
import collections
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
def dfs(graph, visited, i, j):
que = collections.deque()
que.append([i, j])
visited[i][j] = True
while que:
x, y = que.popleft()
for move_x, move_y in directions:
next_x, next_y = x + move_x, y + move_y
if next_x >= n or next_x < 0 or next_y >= m or next_y < 0:
continue
if graph[next_x][next_y] == 1 and not visited[next_x][next_y]:
visited[next_x][next_y] = True
que.append([next_x, next_y])
if __name__ == '__main__':
n, m = list(map(int, input().split()))
graph = []
for _ in range(n):
graph.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 graph[i][j] == 1:
res += 1
dfs(graph, visited, i, j)
print(res)
参考文章:
岛屿数量·广搜版