返回题解分享
讨论 / 题解分享/ 帖子详情

岛屿个数(编程题) - 题解

from collections import deque

dirsea =[(0,1),(0,-1),(1,0),(-1,0),(1,1),(-1,-1),(-1,1),(1,-1)]
dirland = [(1,0),(-1,0),(0,1),(0,-1)]

def bfsland(x,y):
    qland = deque()
    qland.appendleft((x,y))
    vis_island[x][y] =1
    while qland:
        x,y = qland.popleft()
        for l in range(4):
            nx = x+dirland[l][0]
            ny = y+dirland[l][1]
            if nx>=m or nx<0 or ny>=n or ny<0:
                continue
            if maze[nx][ny] =='1' and vis_island[nx][ny]==0:
                vis_island[nx][ny] =1
                qland.appendleft((nx,ny))




def bfssea(x,y):
    global ans
    qsea = deque()
    qsea.appendleft((x,y))
    vis_sea[x][y] = 1
    while qsea:
        x,y = qsea.popleft()
        for k in range(8):
            nx =x+dirsea[k][0]
            ny = y + dirsea[k][1]
            if nx>=m or nx<0 or ny>=n or ny<0:
                continue

            if maze[nx][ny] == '0' and vis_sea[nx][ny]==0:
                qsea.appendleft((nx,ny))
                vis_sea[nx][ny]=1

            if maze[nx][ny] =='1' and vis_island[nx][ny]==0:
                ans +=1
                bfsland(nx,ny)













for i in range(int(input())):
    m,n = map(int,input().split())
    maze = []
    ans = 0
    for i in range(m):
        maze.append(input())

    vis_island = [[0]*n for i in range(m)]
    vis_sea = [[0]*n for i in range(m)]
    flag  =0
    for i in range(m):
        for j in range(n):
            if (not i or i == m-1 or j ==n-1 or not j):
                if maze[i][j] == '0' and vis_sea[i][j]==0:
                    flag=1
                    bfssea(i,j)

    if not flag:
        ans =1

    print(ans)
0 回复 0 转发 0 喜欢 2 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!