编写程序求鞍点
时间: 2024-02-28 07:55:49 浏览: 64
鞍点,也叫做马鞍点,指的是矩阵中的一个元素,它在所在行上是最大值,在所在列上是最小值。下面是一个求矩阵鞍点的Python程序示例:
```python
# 定义矩阵
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 遍历矩阵,找到鞍点
for i in range(len(matrix)):
row_max = max(matrix[i]) # 行最大值
col_index = matrix[i].index(row_max) # 行最大值所在列的索引
col_min = row_max # 列最小值
for j in range(len(matrix)):
if matrix[j][col_index] < col_min: # 如果发现更小的值,则更新列最小值
col_min = matrix[j][col_index]
if row_max == col_min: # 如果行最大值等于列最小值,则找到鞍点
print("鞍点坐标为:({}, {}),值为:{}".format(i, col_index, row_max))
```
在这个示例中,我们定义了一个3x3的矩阵,然后遍历整个矩阵,对于每一行,找到行最大值及其所在列的索引,然后在该列上查找最小值,如果最小值等于行最大值,则找到了一个鞍点。最后,程序输出鞍点的坐标及其值。
相关问题
编写程序求出二维数组中的鞍点。
以下是一个编写程序求出二维数组中鞍点的例子:
```python
def find_saddle_point(matrix):
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
row_max = max(matrix[i])
col_index = matrix[i].index(row_max)
col_min = matrix[i][col_index]
for j in range(rows):
if matrix[j][col_index] < col_min:
col_min = matrix[j][col_index]
if row_max == col_min:
return i, col_index, row_max
return "No"
# 测试例子
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = find_saddle_point(matrix)
print(result) # 输出:(2, 0, 7)
```
C++编写程序求出二维数组中的鞍点。
```cpp
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
bool hasSaddlePoint = false;
for (int i = 0; i < 3; i++) {
int maxInRow = matrix[i][0];
int colIndex = 0;
for (int j = 1; j < 3; j++) {
if (matrix[i][j] > maxInRow) {
maxInRow = matrix[i][j];
colIndex = j;
}
}
bool isSaddlePoint = true;
for (int k = 0; k < 3; k++) {
if (matrix[k][colIndex] < maxInRow) {
isSaddlePoint = false;
break;
}
}
if (isSaddlePoint) {
cout << "Saddle point found at position (" << i << "," << colIndex << ") with value " << maxInRow << endl;
hasSaddlePoint = true;
}
}
if (!hasSaddlePoint) {
cout << "No saddle point found in the matrix." << endl;
}
return 0;
}
```
阅读全文