如何使用Java找到矩阵的鞍点?

如何找到矩阵的鞍点,这是行中的最高数字,同时是使用Java的列中的最高数字?

例如,使用此矩阵:

| 7 2 |

| 1 3 |

| 5 8 |

马鞍点是:7和8。

这是我编写的代码部分,用于查找行和列中的最大数字。

int NumRow = 3; int NumCol = 2; int [] matrix = new int [NumRow][NumCol]; for ( int i = 0; i < NumRow; i++) { max = matrix[i][0]; for ( int j = 1; j  max) { max = matrix[i][j]; } } System.out.print(max+" "); } System.out.println("\n"); for ( int c = 0; c < NumCol; c++) { largest = matrix[c][0]; for (int r = 0; r  largest){ largest = matrix[r][c]; } } System.out.print(largest+" "); } 

输出是:

7 3 8

7 8

现在我想使用上面的定义找到鞍点。

不幸的是我得走了。 看起来你最终会到达那里。 这是一个基于您的描述的解决方案,您描述的方式应该有效。

它不是最有效的,你应该改进它。 你也不应该把它作为一个任务提交,这样做只会欺骗自己,你会发现未来的任务很难。

 public class SaddlePointerFinder{ public static void main(String[] args){ int [] [] matrix = { { 7, 2 }, { 1, 3 }, { 5, 8 }, }; // i loops though columns for(int x = 0; x highestOnTheRow) { // update the highest highestOnTheRow = matrix[y][x]; indexOfHighest = y; } } // After checking the whole row and finding the highest, check if it's highest on the column boolean highest = true; // here, i checks goes through each row using that column. for(int i = 0; i highestOnTheRow) { // one which was higher was found :( highest = false; } } if(highest){ System.out.println("If the forumla is correct, this is a saddle point: " + highestOnTheRow); } } } 

来自维基百科 (强调我的):

鞍点是矩阵的一个元素,它既是其列中的最大元素,也是其行中的最小元素。

您可以通过按行顺序遍历矩阵来确定它:

  • 创建一个数组来存储当前列的最大值

  • 在运行中存储当前行最小值并将其存储在数组中

完成此操作后,您可以比较两个索引是否同时出现,以便您拥有一个同时具有column-max和row-min的索引。

注意:根据维基百科的定义,你的example-matrix没有任何鞍点。