zoukankan      html  css  js  c++  java
  • 用递归统计矩阵的连通个数

    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
  • 相关阅读:
    EncodeLDPC校验矩阵H的高斯变换
    Linuxubuntu学习(一)
    tcp通信
    HTTP协议,超文本传输协议
    局部变量成员变量
    线程
    正则表达式
    面向对象
    String类
    Object类
  • 原文地址:https://www.cnblogs.com/hello-dummy/p/14433187.html
Copyright © 2011-2022 走看看