随机生成杨氏矩阵查找目标数
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<errno.h>
typedef struct found{
int row;
int column;
}Found;
int main(int argc,char *argv[]){
srand((unsigned int)time(0));
int row_limit=15,ch=0,len_last=0,input=0,start=0,found_flag=0,found_count=0;//row取太大或太小观赏性不佳
Found *founds=NULL;
//for(fputs("Input the row(column)(0Quit):",stdout),ch=scanf("%d",&row);ch!=1||row<0;fputs("Input the row(column)(0Quit):",stdout),ch=scanf("%d",&row))
// while(getchar()!=10);
//while(getchar()!=10);
/*生成杨氏矩阵*/
int **arr=(int **)calloc(row_limit,sizeof(int *));
if(!arr){
printf("ERROR:%s\n",strerror(errno));//必须include:string.h+errno.h两个文件
exit(1);
}
for(int i=0;i<row_limit;*(arr+i)=(int *)calloc(row_limit,sizeof(int)),i++);
for(int i=0;i<row_limit;i++)
for(int j=0;j<row_limit;j++){
if(!i&&!j)
arr[i][j]=rand()%10+1;
else if(i&&!j)
arr[i][j]=arr[i-1][j]+rand()%10+1;
else if(!i&&j)
arr[i][j]=arr[i][j-1]+rand()%10+1;
else
arr[i][j]=(arr[i-1][j]>arr[i][j-1]?arr[i-1][j]:arr[i][j-1])+rand()%50+1;
}
/*输入目标数*/
for(fputs("Input the number:",stdout),ch=scanf("%d",&input);ch!=1;fputs("Input the number:",stdout),ch=scanf("%d",&input))
while(getchar()!=10);
while(getchar()!=10);
/*根据左上角和右下角数判断目标数是否存在*/
if(input<arr[0][0]||input>arr[row_limit-1][row_limit-1]){
printf("Can't found the number <%d> in arr.\n",input);
exit(0);
}
/*从右上角开始扫描目标数*/
int row=0,column=row_limit-1;
while(row<=row_limit-1&&column>=0){
if(arr[row][column]>input)
column--;
else if(arr[row][column]<input)
row++;
else{
found_flag=1;
found_count++;
if(found_count==1)
founds=(Found *)calloc(found_count,sizeof(Found));
else if(found_count>1){
Found * ptemp=(Found *)realloc(founds,found_count*sizeof(Found));
if(ptemp){
founds=ptemp;
ptemp=NULL;
}
}
founds[found_count-1].row=row;
founds[found_count-1].column=column;
column--;
}
}
/*显示杨氏矩阵*/
for(int temp=arr[row_limit-1][row_limit-1];temp;temp/=10,len_last++);
fputs("The arr is:\n",stdout);
for(int i=0;i<row_limit;i++){
for(int j=0;j<row_limit;printf("%-*d",len_last+1,arr[i][j]),j++);
fputc(10,stdout);
}
/*显示结果*/
if(found_flag){//问:怎么通过三目操作符进行条件判断输出?"printf打印变量":"谢谢惠顾";
printf("Found the input number <%d> in ",input);
for(int i=0;i<found_count;i++)
printf("arr[%d][%d],",founds[i].row,founds[i].column);
fputs("\b.\n",stdout);
}
else
printf("Couldn't found the input number <%d> in arr.\n",input);
/*清理动态内存*/
for(int i=0;i<row;free(arr[i]),i++);
free(arr);
arr=NULL;
if(founds)
free(founds);
founds=NULL;
return 0;}