二维数组鞍点的定义:存在一个二维数组a[n][m],有一个元素a[i][j],在i行中它是最大的元素,在j列中它是最小的元素,则认为a[i][j],关于二维数组中的鞍点的个数的问题,未找到准确的定义,有的书上说是一个二维数组最多只有一个鞍点,但是有的就说是可以有多个。
下面的代码实现了寻找二维数组中的一个鞍点的问题。
#include <stdio.h>
#include <stdlib.h>
int main(){
int a[100][100];
printf("Please input the order of the matrix:");
int n,m,count=0;
scanf("%d %d",&n,&m);
//Initialization the matrix.
printf("Please input the number of your matrix.\n");
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%d",&a[i][j]);
}
}
for(int i=0;i<n;i++){
int max=a[i][0],tempi=i,tempj=0;
for(int j=1;j<m;j++){//Find the max number of the row and noted the cols of the max number.
if(a[i][j]>max){
max=a[i][j];
tempj=j;
}
}
int flag=1;
for(int k=0;k<n;k++){//Verify whether the number "max" is the least number in this cols
//If the number that in this row is smaller than the number "max"
//That can explain the number "max" is not a saddle point.
if(a[k][tempj]<max){
flag=0;
break;
}
}
if(flag==1){//当前的数字为鞍点
count++;
printf("\nThe saddle point of this matrix is (%d,%d):%d\n",tempi,tempj,max);
}
}
if(count==0){
printf("This matrix have no saddle point.\n");
}
return 0;
}
对应的测试数据和结果如下:
(1)存在鞍点的情况
Please input the order of the matrix:4 5
Please input the number of your matrix.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
The saddle point of this matrix is (0,4):5
(2)不存在鞍点的情况
Please input the order of the matrix:4 5
Please input the number of your matrix.
1 2 3 4 11
2 4 6 8 12
3 6 9 10 15
4 8 12 16 7
This matrix have no saddle point.