全RE求调,小一点的数据都是对的,可能是内存不够,或者是python本身的弊端?
查看原帖
全RE求调,小一点的数据都是对的,可能是内存不够,或者是python本身的弊端?
1367100
sunxiaochuan152楼主2024/12/18 23:37
from collections import deque

d = [[1, 0], [0, 1], [-1, 0], [0, -1]]


def bfs(x, y):
    cnt = 1
    #visited = [[0 for _ in range(n)] for _ in range(n)]
    visited[x][y] = 1
    queue = deque([(x, y)])
    while queue:
        x, y = queue.popleft()
        for dx, dy in d:
            tx = x + dx
            ty = y + dy
            if 0 <= tx < n and 0 <= ty < n and visited[tx][ty] == 0 and l[tx][ty]!= l[x][y]:
                visited[tx][ty] = 1
                queue.append((tx, ty))
                cnt += 1
    return cnt


n, m = map(int, input().split())
l = [list(map(int, input())) for i in range(n)]
visited = [[0 for _ in range(n)] for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    print(bfs(a - 1, b - 1))
    for i in range(n):
        for j in range(n):
            visited[i][j] = 0
2024/12/18 23:37
加载中...