用递归统计矩阵的连通个数

def getConnectedNum(mat):
    cnt = 0
    h = len(mat)
    for i in range(h):
        w = len(mat[i])
        for j in range(w):
            if mat[i][j] == 0:
                cnt = cnt + 1
                seekConnected(mat, i, j, h, w)
          # 打印
for i in range(h): for j in range(w): print(mat[i][j], end=" ") print() print() return cnt def seekConnected(mat, i, j, h, w, border = None): if i < 0 or j < 0 or i > h-1 or j > w-1 or mat[i][j] == 1: return mat[i][j] = 1 seekConnected(mat, i - 1, j, h, w) seekConnected(mat, i + 1, j, h, w) seekConnected(mat, i, j - 1, h, w) seekConnected(mat, i, j + 1, h, w) pass if __name__ == '__main__': mat = [ [0, 0, 1, 1, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 1, 1, 1] ] print(getConnectedNum(mat)) pass
原文地址:https://www.cnblogs.com/hello-dummy/p/14433187.html