C ++ implementation find all saddle points

C ++ implementation find all saddle points

Realization of ideas

A minimum value in the matrix at the same time i-th row j-th column is the minimum we call saddle point. The following describes the method for finding the saddle point in two-dimensional array of memory:
1. First, find the minimum value of each line, which is stored in an array row_min [M], M is the number of rows of the array;
2. First, two position marks disposed min_i ordinate min_j, a column representing the minimum value and the minimum value of the abscissa of a row.
Each element 3 through the array, if the value of the element is equal to the minimum of the line, i.e. it is equal to the minimum number of lines corresponding row_min, this element is referred to herein temporary flag, then let min_i, min_j value of the flag The abscissa and ordinate.
4. The traversing element corresponding to the row, if the flag is smaller than the elements, so that the abscissa is equal to min_i smaller elements. Finally, see if min_i also equal to the flag of the horizontal axis, if it means finding a saddle point and outputs it.

c ++ source code

#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
#define M 4
#define N 5
void FindSaddlePoint(int arr[M][N])
{
 int min_i, min_j;
 int min_row[M];
 for (int i = 0; i < M; i++)//找到每行元素的最小值并将其存入min_row数组中
 {
  int k = 0;
  for (int j = 0; j < N; j++)
   if (arr[i][j] < arr[i][k])
    k = j;
  min_row[i] = arr[i][k];
 }
 for (int i = 0; i < M; i++)
 {
  for (int j = 0; j < N; j++)
  {
   if ( min_row[i]== arr[i][j])//该元素的值等于该行元素的最小值
   {
    min_j = j;
    min_i = i;
    for (int k = 0; k < M; k++)//寻找该行元素对应的列的最小值
     if (arr[min_i][min_j] > arr[k][min_j])
      min_i = k;
    if (min_i == i)//该列元素的最小值就是上述的行最小值
     cout << "(" << min_i << "," << min_j << ")" << setw(4) << arr[min_i][min_j] << endl;
   }
  }
 }
}
int main()
{
 int arr[M][N];
 srand(time(0));
 for(int i=0;i<M;i++)
  for (int j = 0; j < N; j++)
  {
   arr[i][j] = rand() % (M*N);
  }
 for (int i = 0; i < M; i++)
 {
  for (int j = 0; j < N; j++)
   cout << setw(4)<<arr[i][j];
  cout << endl;
 }
 cout << "Saddle Point:" << endl;
 FindSaddlePoint(arr);
 system("pause");
 return 0;
}

Published 16 original articles · won praise 18 · views 4141

Guess you like

Origin blog.csdn.net/qq_42103091/article/details/89058049