编写程序,找一找一个二维数组中的鞍点(C#)
一、效果如下;
二、代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Test5 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine("----欢迎进入计算矩阵鞍点系统----"); 14 int[,] arr = new int[100, 100];//该数组 15 int m, n; 16 Console.Write("请输入二维数组的行数(小与100):"); 17 m = int.Parse(Console.ReadLine());//矩阵行数 18 Console.Write("请输入二维数组的列数(小与100):"); 19 n = int.Parse(Console.ReadLine());//矩阵列数 20 int i, j; 21 //输入该矩阵 22 Console.WriteLine("请依次换行输入" + m + "x" + n + "的矩阵"); 23 for (i = 0; i < m; i++)//行 24 { 25 for (j = 0; j < n; j++)//列 26 { 27 arr[i, j] = int.Parse(Console.ReadLine());//需要依次换行输入,若是一次性输入,会报错 28 } 29 } 30 //输出打印该矩阵 31 32 for (i = 0; i < m; i++) 33 { 34 if (i == m / 2) 35 { 36 Console.Write("A = "); 37 } 38 for (j = 0; j < n; j++) 39 { 40 if (i == m / 2) 41 { 42 Console.Write(arr[i, j] + " "); 43 } 44 else 45 { 46 Console.Write(" " + arr[i, j]); 47 } 48 } 49 Console.WriteLine(); 50 } 51 52 int row_max;//先找到该行的最大值 53 int[] an_point = new int[100];//存储矩阵中所有鞍点 54 int count = 0;//鞍点个数 55 int temp1 = 0, temp2 = 0;//暂时保存该行最大值的位置 56 int[] x = new int[100];//保存鞍点的横坐标 57 int[] y = new int[100];//保存鞍点的纵坐标 58 bool flag = false;//判断是否是鞍点 59 60 for (i = 0; i < m; i++) 61 { 62 row_max = arr[i, 0];//令某行最大的等于该行第一个数 63 for (j = 0; j < n; j++) 64 { 65 if (row_max < arr[i, j]) 66 { 67 row_max = arr[i, j];//找到该行最大值 68 //记录该数的位置 69 temp1 = i; 70 temp2 = j; 71 } 72 } 73 //找到最大值后判断该值在该列是否是最小值 74 for (int k = 0; k < m; k++) 75 { 76 if ((arr[k, temp2] < row_max) || (arr[k, temp2] == row_max && k != temp1))//不是最小值 77 { 78 flag = false; 79 break; 80 } 81 else//是最小值 82 { 83 flag = true; 84 } 85 } 86 //是鞍点 87 if (flag == true) 88 { 89 count++;//鞍点个数加一 90 an_point[count] = arr[temp1, temp2];//保存鞍点 91 //保存鞍点位置 92 x[count] = temp1 + 1; 93 y[count] = temp2 + 1; 94 } 95 } 96 if (count == 0) 97 { 98 Console.WriteLine("该矩阵无鞍点!"); 99 } 100 else 101 { 102 Console.WriteLine("该矩阵有" + count + "个鞍点"); 103 Console.WriteLine("分别是:"); 104 for (int p = 1; p <= count; p++) 105 { 106 Console.Write("A[" + x[p] + "," + y[p] + "]="); 107 Console.WriteLine(an_point[p]); 108 } 109 } 110 111 Console.ReadKey(); 112 } 113 } 114 }