Problem Description:
a m * n (1 <n and m <= 10) matrix, each matrix row there is only one maximum value, a minimum value for each column only requires the matrix to find the saddle point. What is a saddle point? I.e., a matrix element, that is the maximum value of the row, where the column is the minimum . If the required output saddle point coordinates and its value, if there is no output saddle point "no saddle point"
Solutions:
- Make a first outer loop, the line number from the beginning row, row line to find the maximum element a [row] [col], col row for the first row under the column numbers where the largest element
- Then followed to see if the element has respective col column is smaller than a [row] [col] of
- Subsequently not found or determined in accordance with a further found
Code:
#include <stdio.h>
const int N=11;
int AnDian(int a[N][N],int n,int m,int *r,int *c);//在n*m数组中找鞍点,如果找到用*r,*c存放鞍点行号、列号,返回1;否则返回0
int main(void)
{
int a[N][N],r,c;//r,c分别存放鞍点的行号和列号
int n,m;
printf("输入n m:\n");
scanf("%d %d",&n,&m);
printf("接着输入n*m个矩阵元素:\n");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
}
}
int res=AnDian(a,n,m,&r,&c);
if(res)
{
printf("鞍点元素下标,以及元素值为:");
printf("(%d,%d) %d\n",r,c,a[r][c]);
}
else
{
printf("not found!\n");
}
return 0;
}
int AnDian(int a[N][N],int n,int m,int *r,int *c)
{
int flag=0;//0表示没找到,1表示找到,初始化未找到
for(int row=1;row<=n;row++)//该层循环用于控制指向矩阵的行数
{
int col=1;//假设row行的第1列元素是row行的最大元素
int j;//①用于控制第一个内层for循环次数 以及 ②判断是否完全循环完第二个内层for循环次数
for(j=2;j<=m;j++)//用于找出row行的最大元素的col下标,col随着元素的增大不断更新
{
if(a[row][j]>a[row][col])
{
col=j;
}
}
for(j=1;j<=n;j++)//将该col下标元素与其上下行元素比较,看是否是第col列最小元素
{
if(a[j][col]<a[row][col])
{
break;//若没有提前退出当前循环(此时j==n+1),则a[row][col]是第col最小元素
}
}
if(j==n+1)
{
flag=1;
*r=row;
*c=col;
break;
}
}
return flag;
}
Output:
I found in doing the program can only return to the saddle point of the first found, and its index, but a few carefully thought matrix (matrix and have more repeat elements), we found only one saddle point or to a nor both cases, God can see the big explain it? Or a matrix can have multiple saddle points but I did not expect. headache!