思路:

        使用DFS搜索陆地。遍历网格,遇到陆地即为入口,陆地数加一。然后递归周围的四个节点。注意使用标记数组,标记已经访问过的点。

#岛屿数量
# 4 5
# 1 1 1 1 0
# 1 1 0 1 0
# 1 1 0 0 0
# 0 0 0 0 0
# 输出:1

# 4 5
# 1 1 0 0 0
# 1 1 0 0 0
# 0 0 1 0 0
# 0 0 0 1 1
#输出: 3
def Island(grid,m,n):
    res=0
    visited=[[0]*n for _ in range(m)]
    dirs=[(0,1),(0,-1),(1,0),(-1,0)]  #四个搜索方向
    #DFS搜索函数
    def dfs(x,y):
        nonlocal res
        if x<0 or x>=m or y<0 or y>=n:
            return
        if grid[x][y]!=1 or visited[x][y]!=0:
            return
        visited[x][y]=1
        for dx, dy in dirs:
            nx = x + dx
            ny = y + dy
            dfs(nx,ny)
            # if 0 <= nx < m and 0 <= ny < n and visited[nx][ny] == 0 and grid[nx][ny] == 1:
            #     dfs(nx,ny)
    #遍历网格
    for i in range(m):
        for j in range(n):
            if grid[i][j]==1 and visited[i][j]==0:
                res+=1
                dfs(i, j)
    print(res)
    return res
def main():
    m,n=map(int,input().split())
    grid=[]
    for i in range(m):
        nums=list(map(int,input().split()))
        grid.append(nums)
    Island(grid,m,n)
if __name__=="__main__":
    main()

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐