编程基本功——寻找矩阵中的“鞍点”

一、问题分析

    在所在行中最大,在所在列中最小。所以一个矩阵最多只有一个鞍点。

     所以可以逐行寻找鞍点。先找出某行中最大的元素,再将该元素与同列中其他元素进行比较,若该元素同时是所在列中最小的元素,则它就是鞍点。

二、源码

   1: #include <stdio.h>
   2:  
   3: int GetSaddlePoint(int *x, int *y, int (*A)[5], int m, int n)
   4: {
   5:     int max, i, j, k, flag;
   6:     for (i = 0; i < m; ++i)
   7:     {
   8:         max = 0;
   9:         flag = 1;
  10:         for (j = 1; j < n; ++j)
  11:         {
  12:             if (A[i][j] > A[i][max])
  13:             {
  14:                 max = j;
  15:             }
  16:         }
  17:  
  18:         for (k = 0; k < n; ++k)
  19:         {
  20:             if (A[i][max] == A[i][k] && max != k)
  21:             {
  22:                 flag = 0;
  23:                 break;
  24:             }
  25:         }
  26:  
  27:         if (flag == 1)
  28:         {
  29:             for (k = 0; k < m; ++k)
  30:             {
  31:                 if (A[k][max] <= A[i][max] && k != i)
  32:                 {
  33:                     flag = 0;
  34:                     break;
  35:                 }
  36:             }
  37:         }
  38:  
  39:         if (flag == 1)
  40:         {
  41:             *x = i;
  42:             *y = max;
  43:             return 1;
  44:         }
  45:     }
  46:  
  47:     return 0;
  48: }
  49:  
  50: int main()
  51: {
  52:     int A[5][5], i, j, x, y;
  53:     printf("please input some digit into the 5*5 matrix\n");
  54:     for (i = 0; i < 5; ++i)
  55:     {
  56:         for (j = 0; j < 5; ++j)
  57:         {
  58:             scanf("%d", &A[i][j]);
  59:         }
  60:     }
  61:  
  62:     if (GetSaddlePoint(&x, &y, A, 5, 5))
  63:     {
  64:         printf("\n SaddlePoint is (%d , %d)\n", x+1, y+1);
  65:     }
  66:     else
  67:     {
  68:         printf("there is no SaddlePoint\n");
  69:     }
  70:     return 0;
  71: }

你可能感兴趣的:(编程)