python - 找到所有的块
问题描述
我对 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)
任何帮助将不胜感激。
解决方案
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 算法来解决这个问题。引用可能不足以理解逻辑。如果您对此解决方案有任何疑问,请告诉我!
推荐阅读
- postgresql - 哪种数据类型用于在 postgresql 中存储 firebase uid
- javascript - 使用 C# 和 Web API 的 jsTree 延迟加载
- c# - 如何用 Microsoft.Azure.Storage.Blob 替换 Microsoft.WindowsAzure.Storage
- python - Pandas 使用多个条件进行排序和重组
- javascript - 如果我第二次下载 printscreen,html2canvas 错误
- javascript - vuejs中如何获取querySelector元素?
- rust - 如何在 Rust 中将图像的像素设置为黑色
- javascript - 如何从 json 文件中删除一个值并将其作为请求在 Cypress 中传递
- android - InCallService 和 ConnectionService 的区别
- algorithm - 到达终点的最短距离