杨氏矩阵查找数字是否存在

时间:2021-12-10 00:55:55

杨氏矩阵示例:

1  2  3
4 6 8
7 8 10

利用返回型参数返回列数和行数

#include<stdio.h>

//1 2 3
//5 6 9
//8 7 13
int Findnum(int arr[3][3],int* x,int* y, int num) {
int a = 0;
int b = *y - 1;
while (a < *x && b >= 0) {
if (arr[a][b] == num) {
*x = a;
*y = b;
return 1;
}
else if (arr[a][b] > num) {
b--;
}
else {
a++;
}
}
}
int main() {
int arr1[3][3] = { {1,2,3},{5,6,9},{8,7,13} };
int num = 5;
int x = 3;
int y = 3;
int ret = Findnum(arr1,&x,&y, num);
if (ret == 1) {
printf("找到了,在第%d行%d列",x+1,y+1);
}
else {
printf("没找到");
}
return 0;
}