书中实现的是从右上角找起的算法,而我是从左下角找起的。如果比左下角数大,则所查找的数都在左下角右边三列内;否则,在左下角上面那三行里。
#include <iostream>
using namespace std;
#define ROW 4
#define COLOMN 4
bool findnum(int matrix[][COLOMN], int row,int colomn, int num)//二维数据作为参数传递时,一定要给出第二维的大小
{
bool found = false;
int i = row-1, j = 0;
while(i >= 0 && j < colomn)
{
cout<<matrix[i][j]<<endl;
if (num == matrix[i][j])
{
found = true;
break;
}
if (num < matrix[i][j])
i = i-1;
else
j = j+1;
}
return found;
}
int main()
{
int matrix[ROW][COLOMN]={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COLOMN; j++)
cout<<matrix[i][j]<<" ";
cout<<endl;
}
bool found = false;
int num = 0;
cout<<"pls input the num you want to find: ";
cin>>num;
found = findnum(matrix,ROW,COLOMN,num);
if (found)
cout<<"find the num it the matrix";
else
cout<<"cannot find the num in the matrix";
return 0;
}
本文介绍了一种从左下角开始查找矩阵中特定数值的算法,并通过C++代码实现。重点阐述了算法的运行原理、步骤及在不同情况下的查找策略,包括比较当前元素与目标值的关系来确定搜索方向。
609

被折叠的 条评论
为什么被折叠?



