寻找数组中的马鞍点

xiaoxiao2021-02-28  29

#include<iostream> #include<iomanip> #include<stdlib.h> #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() { cout<<"请输入二维数组("<<M<<"*"<<N<<"):"<<endl; ElemType array[M][N]; CreateArray(array); SaddlePoint(array, M, N); cout<<endl<<endl; return 1; } ElemType CreateArray(ElemType array[M][N]) { int i,k,j; for(i=0;i<M;i++) { for(j=0;j<N;j++) { cin>>array[i][j]; } cout<<endl<<endl; } cout<<endl; 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<<endl<<"("<<i<<","<<s[j]<<","; cout<<array[i][s[j]]<<")"; } } } } if(0 == count) { cout<<endl<<"No any saddle!"; } else { cout<<endl<<"There are "<<count<<" saddles!"; } }
转载请注明原文地址: https://www.6miu.com/read-2627687.html

最新回复(0)