原题:若在矩阵A[n*n]中存在一个元素a[i-1][j-1]满足a[i-1][j-1]是第 i 行元素中最小且又是第 j 列元素中的最大值,则称此元素为该矩阵的一个马鞍点.试设计一个求矩阵所有马鞍点的
#include
#include
#include
#include//控制输出格式的头文件
#include
#define N 3//列数
#define M 3//行数
#define ElemType int
using namespace std;
ElemType CreateArray(ElemType array[M][N]);//函数原型声明
void SaddlePoint(ElemType array[M][N], int m, int n);//函数原型声明
int main()
{
ElemType array[M][N];
CreateArray(array);
SaddlePoint(array, M, N);
cout<
return 1;
}
ElemType CreateArray(ElemType array[M][N])
{//生成一个数据元素随机生成的二维数组,用于测试
int i,k,j;
srand((unsigned)time(NULL));
for(i=0;i
{
for(j=0;j
{
k=rand()%100 + 9;
cout.width(4);//设置数字输出时的宽度,每一次输出都要设置
cout<
array[i][j] = k;
}
cout<
}
cout<
return 1;
}
void SaddlePoint(ElemType array[M][N], int m, int n)//寻找马鞍点的函数
{
ElemType *s = new ElemType[n+1];//存储某一行的元素值最小的元素下标
int c;//表示此行的元素值等于最小值的元素的个数
int count = 0;//马鞍点的个数
int i, j, k;
ElemType min;//某一行的最小元素值
for(i = 0; i < m; i++)
{
min = array[i][0];
c = 1; s[1] = 0;//当前已得的元素值最小的元素下标与个数
for(j = 1; j < n; j++)
{
if(array[i][j] < min)
{
min = array[i][j];//array[i][j]为最新的最小值
c = 1; s[1] = j;//当前已得的元素值最小的元素下标与个数
}
else if(min == array[i][j])
{
c++;//元素值最小的元素的个数增1
s[c] = j;
}
}
for(j = 1; j <= c; j++)
{
k = 0;
//判断是否第 s[j] 列有大于 a[i][s[j]]的元素
while(k < m && (array[i][s[j]] >= array[k][s[j]]))
{
k++;
if(k >= m)
{//表示array[i][s[j]]是第s[j]列的最大元素,它是马鞍点
count++;//马鞍点个数增1
cout<
cout<
}
}
}
}
if(0 == count)
{
cout<
}
else
{
cout<
}
}