數(shù)組數(shù)字從左到右遞增
從上到下遞增
綠色是剩下查找范圍丽惶, 永遠(yuǎn)是跟右上角的數(shù)字比較大小
類(lèi)似
image.png
image.png
image.png
image.png
image.png
#include <iostream>
#include <stack>
//** matrix 數(shù)組
//** row 行
//** column 列
//** number 要查找的數(shù)字
bool Find(int * matrix, int rows ,int columns, int number) {
bool found = false;
// 算法的核心思想是從右上角往左下角查找,因?yàn)樽筮叺臄?shù)字比右邊的數(shù)字小抡秆,上邊的數(shù)字比下邊小儒士,所以?xún)蛇呁瑫r(shí)縮小范圍
if (matrix != NULL && rows > 0 && columns > 0) {
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0 ) {
if (matrix[row * columns + column] == number) { // 如果發(fā)現(xiàn)數(shù)字就跳出循環(huán)了
found = true;
break;
} else {
if (matrix [row * columns + column] > number) { // 比右邊的數(shù)字小,則查找左邊的诅福,比右邊的數(shù)字大拖叙,則這一行就不可能有要找的數(shù)字
column--;
} else {
row++;
}
}
}
return found;
}
return found;
}
int main() {
int matrix[] = {1,2,8,9,
2,3,9,12,
4,7,10,13,
6,8,11,15};
if (Find(matrix, 4, 4, 7)) {
printf("found\n");
} else {
printf("not found\n");
}
return 0;
}