代码如下
//二维矩阵查找指定数值,————分治法,每次从右上角比较
//矩阵每行从左至右递增,每列从上至下递增
#include <iostream>
#include <vector>
using namespace std;
static int count=0;
void searchx(vector<vector<int>> &matrix, int n, int j, int k, int target)
{
if (j >= n || k < 0)
{
cout<<"-1"<<endl;
return;
}
if (target == matrix[j][k])
{
count++;
cout << j << "," << k<<":"<<target<<endl;
}
else if (target < matrix[j][k])
{
count++;
k--; // 减少一列
searchx(matrix, n, j, k, target);
}
else
{
count++;
j++; // 减少一行
searchx(matrix, n, j, k, target);
}
}
int main()
{
int n;
cin >> n;
vector<vector<int>> matrix(n, vector<int>(n));
for (int i = 0; i < n; i++)
{
for (int y = 0; y < n; y++)
{
cin >> matrix[i][y];
}
}
int target;
cin >> target;
searchx(matrix, n, 0, n - 1, target);
cout<<"比较次数:"<<count;
return 0;
}