该算法针对 4×4 矩阵和 2×2 子矩阵进行硬编码。否则,作为一种暴力算法,它看起来不错。
我会表达如下:
outerRow:
for (int or = 0; or <= a.length - b.length; or++) {
outerCol:
for (int oc = 0; oc <= a[or].length - b[0].length; oc++) {
for (int ir = 0; ir < b.length; ir++)
for (int ic = 0; ic < b[ir].length; ic++)
if (a[or + ir][oc + ic] != b[ir][ic])
continue outerCol;
System.out.println("Submatrix found at row " + or + ", col " + oc);
break outerRow;
}
}
如果你想要更高效的东西,我建议你将它们展平,如下所示:
{ 2,3,5,7, 5,8,3,5, 7,6,9,2, 3,8,5,9 }
并在此序列中搜索以下模式:
{ 9,2, _, _, 5, 9}
使用标准的查找子字符串技术,例如阿霍-科拉西克 or Knuth-Morris-Pratt 算法。 (请注意,您必须跳过一些索引,以避免在序列中间出现新行时出现误报。)