找到所有的块

时间:2019-12-06 13:36:04

标签: python list nested

我对python和编码非常陌生。我有要做的这项作业:

您将在第一行收到矩阵(n)的行,在接下来的n行中,矩阵的每一行都将作为字符串(零和一个用空格隔开)。您必须计算有多少块(水平或对角线连接),例如:

Input:
5
1 1 0 0 0
1 1 0 0 0
0 0 0 0 0
0 0 0 1 1
0 0 0 1 1
Output:
2

Input:
6
1 1 0 1 0 1
0 1 1 1 1 1
0 1 0 0 0 0
0 1 1 0 0 0
0 1 1 1 1 0
0 0 0 1 1 0
Output:
1

Input:
4
0 1 0 1 1 0
1 0 1 1 0 1
1 0 0 0 0 0
0 0 0 1 0 0
Output:
5

我现在想出的代码是:

n = int(input())
blocks = 0

matrix = [[int(i) for i in input().split()] for j in range(n)]

#loop or something to find the blocks in the matrix

print(blocks)

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

def valid(y,x):
    if y>=0 and x>=0 and y<N and x<horizontal_len:
        return True

def find_blocks(y,x):
    Q.append(y)
    Q.append(x)

    #search around 4 directions (up, right, left, down)
    dy = [0,1,0,-1]
    dx = [1,0,-1,0]

    # if nothing is in Q then terminate counting block
    while Q:
        y = Q.pop(0)
        x = Q.pop(0)

        for dir in range(len(dy)):
            next_y = y + dy[dir]
            next_x = x + dx[dir]

            #if around component is valid range(inside the matrix) and it is 1(not 0) then include it as a part of block
            if valid(next_y,next_x) and matrix[next_y][next_x] == 1:
                Q.append(next_y)
                Q.append(next_x)
                matrix[next_y][next_x] = -1


N = int(input())

matrix = []
for rows in range(N):
   row = list(map(int, input().split()))
   matrix.append(row)

#row length
horizontal_len = len(matrix[0])

blocks = 0

#search from matrix[0][0] to matrix[N][horizontal_len]
for start_y in range(N):
    for start_x in range(horizontal_len):

        #if a number is 1 then start calculating
        if matrix[start_y][start_x] == 1:
            #make 1s to -1 for not to calculate again
            matrix[start_y][start_x] = -1
            Q=[]

            #start function
            find_blocks(start_y, start_x)
            blocks +=1

print(blocks)

我使用BFS算法来解决此问题。引用可能不足以理解逻辑。 如果您对此解决方案有疑问,请告诉我!