找出一个二维数组的鞍点,写一个c++
时间: 2024-12-23 09:20:12 浏览: 75
找到一个二维数组中的鞍点是指在一个矩阵中找到两个坐标,其中第一个坐标处的值小于其行上任意元素,而第二个坐标的值大于其列上任意元素。这种特征使得这个位置成为矩阵中的“山谷”。这里有一个简单的C++函数来查找二维数组中的鞍点:
```cpp
#include <vector>
#include <climits>
// 定义一个辅助结构来存储当前最小值和最大值
struct MinMax {
int minRow, maxRow;
int minValue, maxValue;
};
// 功能:找出二维数组的鞍点
std::pair<int, int> findAisle(std::vector<std::vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return std::make_pair(-1, -1); // 空数组
int rows = matrix.size();
int cols = matrix[0].size();
// 初始化全局最小值和最大值以及它们的索引
MinMax globalMinMax = {0, rows - 1, INT_MAX, INT_MIN};
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] < globalMinMax.minValue) {
globalMinMax.minValue = matrix[i][j];
globalMinMax.minRow = i;
}
if (matrix[i][j] > globalMinMax.maxValue) {
globalMinMax.maxValue = matrix[i][j];
globalMinMax.maxRow = i;
}
}
}
// 检查鞍点条件
for (int j = 0; j < cols; ++j) {
if (matrix[globalMinMax.minRow][j] > matrix[globalMinMax.maxRow][j]) {
return std::make_pair(globalMinMax.minRow, j);
}
}
// 如果找不到满足条件的鞍点,返回无效索引
return std::make_pair(-1, -1);
}
阅读全文
相关推荐

















