AcWing BFS相关问题 1098. 城堡问题

import sys
sys.stdin = open('data.txt', 'r')


from collections import deque

grid = []
m, n = map(int, input().split())
for i in range(m):
    grid.append( list(map(int, input().split())) )

def bfs(i, j) -> int:
    que = deque()
    que.append((i, j))
    visited[i][j] = 1
    ans = 0

    while len(que) > 0:
        ii, jj = que.popleft()
        ans += 1
        for mask, new_i, new_j in [ [1, ii, jj-1], [2, ii-1, jj], [4, ii, jj+1], [8, ii+1, jj] ]:
            if grid[ii][jj] & mask == 0 and new_i >= 0 and new_i < m and new_j >= 0 and new_j < n and visited[new_i][new_j] == 0:
                visited[new_i][new_j] = 1
                que.append((new_i, new_j))

    return ans


visited = [[0]*n for _ in range(m)]

cnt, ans = 0, 0
for i in range(m):
    for j in range(n):
        if visited[i][j] == 0:
            val = bfs(i, j)
            ans = max(ans, val)
            print(f'val = {val}')
            cnt += 1

print(cnt)
print(ans)






 

你可能感兴趣的:(AcWing,BFS相关问题,算法)