这是一个非常难的组合问题。实际上 Subgraph Isomorphism Problem 可以简化为您的问题(如果矩阵 A 只有 0-1 个条目,您的问题正是子图同构问题)。已知此问题是 NP 完全问题。
这是一个递归回溯解决方案,它比暴力破解所有可能的解决方案要好一些。请注意,在最坏的情况下,这仍然需要指数级的时间。但是,如果您假设存在解决方案并且不存在歧义(例如,B 中的所有条目都是不同的),则可以在线性时间内找到解决方案。
def locate_columns(a, b, offset=0):
"""Locate `a` as a sublist of `b`.
Yields all possible lists of `len(a)` indices such that `a` can be read
from `b` at those indices.
"""
if not a:
yield []
else:
positions = (offset + i for (i, e) in enumerate(b[offset:])
if e == a[0])
for position in positions:
for tail_cols in locate_columns(a[1:], b, position + 1):
yield [position] + tail_cols
def locate_submatrix(a, b, offset=0, cols=None):
"""Locate `a` as a submatrix of `b`.
Yields all possible pairs of (row_indices, column_indices) such that
`a` is the projection of `b` on those indices.
"""
if not a:
yield [], cols
else:
for j, row in enumerate(b[offset:]):
if cols:
if all(e == f for e, f in zip(a[0], [row[c] for c in cols])):
for r, c in locate_submatrix(a[1:], b, offset + j + 1, cols):
yield [offset + j] + r, c
else:
for cols in locate_columns(a[0], row):
for r, c in locate_submatrix(a[1:], b, offset + j + 1, cols):
yield [offset + j] + r, c
B = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]
A = [[6,8], [16,18]]
for loc in locate_submatrix(A, B):
print loc
这将输出:
([1, 3], [0, 2])