uva352 The Seasonal War-python

计算连通块,dfs

MAXN = 26
dirs = [[1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]]
cnt = 0


def dfs(x, y, m, n):
    flag[x][y] = 1
    for d in dirs:
        nx = x + d[0]
        ny = y + d[1]
        if 0 <= nx < m and 0 <= ny < n and pic[nx][ny] == '1' and flag[nx][ny] == 0:
            dfs(nx, ny, m, n)
while True:
    nn = raw_input()
    if not nn.isdigit():
        break
    n = int(nn)
    flag = [[0 for col in range(MAXN)] for row in range(MAXN)]
    pic = []
    ans = 0
    cnt += 1
    for i in range(n):
        pic.append(raw_input())

    for i in range(n):
        for j in range(n):
            if pic[i][j] == '1' and flag[i][j] == 0:
                dfs(i, j, n, n)
                ans += 1
    print("Image number "+str(cnt)+" contains "+str(ans)+" war eagles.")

你可能感兴趣的:(算法)