#include<stdio.h>
//杨氏矩阵:行和列都递增。例如:
//1 2 3 1 2 3
//2 3 4 和 4 5 6
//3 4 5 7 8 9
// 在 1 2 3 中 查找7,将7和矩阵中右上角元素比较。
// 4 5 6
// 7 8 9
//若右上角元素>7,排除右上角元素所在的 一列。
//若右上角元素<7,排除右上角元素所在的 一行。
//直到找到元素,或者矩阵为空。
int findnum(int arr[3][3], int k, int* px, int* py)
{
int x = 0;
int y = *py - 1;
while (x<=(*px-1)&&y>=0)
{
if(arr[x][y]>k)
{
y--;
}
else if (arr[x][y] < k)
{
x++;
}
else
{
*px = x;
*py = y;
return 1;
}
}
return 0;
}
int main()
{
int arr[3][3] = {
{
1,2,3},{
4,5,6},{
7,8,9} };
int k = 7;
int x = 3;//行数
int y = 3;//列数
int ret = findnum(arr, k, &x, &y);
if (ret==1)
{
printf("找到了。\n");
printf("下标为:%d %d\n", x, y);
}
else
{
printf("没找到。\n");
}
return 0;
}
C语言:杨氏矩阵查找元素。
猜你喜欢
转载自blog.csdn.net/weixin_45275802/article/details/113058036
今日推荐
周排行