计算二进制矩阵中的矩形数

时间:2013-11-29 18:38:53

标签: python-3.x

给定一个nxn二进制矩阵(“#”或_),我们如何计算“#”创建的矩形数量

例如,我们在下面有一个矩形:

_ _ _ # # # _ _ _
_ _ _ # _ # _ _ _
_ _ _ # _ # _ _ _
_ _ _ # _ # _ _ _
_ _ _ # # # _ _ _

1 个答案:

答案 0 :(得分:0)

拿一个完美的NxN方块,你可以这样做:

st='''\
########## 
#####----# 
##--#----# 
##--#----# 
##--#----# 
##--#----# 
#####----# 
########## 
-####----# 
########## '''

def max_size(mat, taken):
    """Find the largest X or a square not taken in the matrix `mat`."""
    nrows, ncols = len(mat), len(mat[0]) 
    assert nrows==ncols 
    dirs=(0,1),(1,0),(1,1) # right, down, right and down
    counts = [[0]*ncols for _ in range(nrows)]
    for i in reversed(range(nrows)):     # for each row
        assert len(mat[i]) == ncols      # matrix must be rectangular
        for j in reversed(range(ncols)): # for each element in the row
            if mat[i][j] != taken:
                if i < (nrows - 1) and j < (ncols - 1):
                    add=1+min(counts[i+x][j+y] for x,y in (dirs))
                else:
                    add=1      # edges 
                counts[i][j]=add        

    for line in counts: print(line)                               
    return max(c for rows in counts for c in rows)   # max X (or Y) number elements

table=[[c for c in s.strip()] for s in st.splitlines()]     

print (max_size(table,'#')**2)