假设我得到了一个矩阵,我需要数一数有多少个附近的十字架。近十字是一个普通交叉的延伸,这意味着在矩阵的整行和整个列中都有相同的数字,但是交集处的数字可能是不同的。我应该如何接近找到十字架,然后测试附近的十字架?
测试用例:
[[1, 1, 1, 1, 1],
[2, 2, 1, 3, 3],
[1, 2, 1, 2, 2],
[5, 5, 1, 6, 6],
[2, 2, 1, 1, 1]]
和
[[1, 1, 0, 1, 1],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0]]
它们中都有一个近十字。
[[1, 1, 0, 1, 1],
[0, 0, 1, 1, 0],
[1, 1, 1, 0, 1],
[0, 0, 1, 1, 0],
[0, 0, 1, 1, 0]]
附近有两个十字架。
发布于 2022-10-02 11:52:21
您可以使用Counter
来识别哪些行最多有一个偏差值。当一个频率至少为n-1
时,这是正确的,其中n
是列数。
然后,您可以列出偏差点(坐标),或行中的所有点(当没有偏差值时)。这给出了一组坐标,每个坐标都可以是一个近十字的交叉点。
转置矩阵并重复上述滤波,然后镜像每个结果点(x对y)。
因此,您将有两组潜在的过境点。这两个集合的交点将给出近交叉的实际交叉点。
下面是该算法的一个实现:
from collections import Counter
def transpose(matrix):
return [list(row) for row in zip(*matrix)]
def potentialcrosspoints(matrix):
n = len(matrix[0])
for i, row in enumerate(matrix):
entries = list(Counter(row).items())
if len(entries) == 1:
for j in range(n):
yield i, j
elif n - 1 in (entries[0][1], entries[1][1]):
yield i, row.index(entries[int(entries[1][1] == 1)][0])
def mirrorpoints(points):
return [(j, i) for i, j in points]
def countnearcrosses(matrix):
return len(set(potentialcrosspoints(matrix)).intersection(
mirrorpoints(potentialcrosspoints(transpose(matrix)))))
# Run of the last example in the question
matrix = [[1, 1, 0, 1, 1],
[0, 0, 1, 1, 0],
[1, 1, 1, 0, 1],
[0, 0, 1, 1, 0],
[0, 0, 1, 1, 0]]
total = countnearcrosses(matrix)
print(total) # 2
https://stackoverflow.com/questions/73924649
复制相似问题