你的矩阵看起来像这样:
a ..... b ..... c
. . . . .
. 1 . 2 .
. . . . .
d ..... e ..... f
. . . . .
. 3 . 4 .
. . . . .
g ..... h ..... i
并具有以下属性:
a,c,g < i
a,b,d < e
b,c,e < f
d,e,g < h
e,f,h < i
所以值在最右下角(例如。i
) 始终是整个矩阵中最大的
如果将矩阵分成 4 个相等的部分,则此属性是递归的。
所以我们可以尝试使用二分查找:
- 探索价值,
- 分成几块,
- 选择正确的作品(以某种方式),
- 转到 1 并添加新的部分。
因此算法可能如下所示:
input: X - value to be searched
until found
divide matrix into 4 equal pieces
get e,f,h,i as shown on picture
if (e or f or h or i) equals X then
return found
if X < e then quarter := 1
if X < f then quarter := 2
if X < h then quarter := 3
if X < i then quarter := 4
if no quarter assigned then
return not_found
make smaller matrix from chosen quarter
这对我来说就像 O(log n),其中 n 是矩阵中的元素数量。这是一种二分搜索,但是是二维的。我无法正式证明它,但类似于典型的二分搜索。