c语言编写程序找出一个二维数组中的鞍点,即该位置上的元素在该行上最大、在该列上最小。也可能没有鞍点。
时间: 2024-11-28 10:13:54 浏览: 28
在C语言中,查找二维数组中的鞍点通常涉及到两层循环,一层用于遍历行,另一层用于比较当前元素与其所在行的最大值和所在列的最小值。以下是一个简单的示例函数,假设输入的数组是已经初始化过的整数矩阵:
```c
#include <stdio.h>
#include <stdbool.h>
typedef struct {
int row;
int col;
} Point;
bool isMinimumInRow(int** arr, int row, int col) {
for (int j = 0; j < arr[row]->row; ++j) {
if (arr[row][j] > arr[row][col]) {
return false;
}
}
return true;
}
bool isMaximumInCol(int** arr, int row, int col) {
for (int i = 0; i < arr->num_rows; ++i) {
if (arr[i][col] < arr[row][col]) {
return false;
}
}
return true;
}
Point findAvalley(int** arr, int num_rows, int num_cols) {
for (int i = 0; i < num_rows; ++i) {
for (int j = 0; j < num_cols; ++j) {
if (isMinimumInRow(arr, i, j) && isMaximumInCol(arr, i, j)) {
return (Point){i, j};
}
}
}
return (Point){-1, -1}; // 表示没有找到鞍点
}
int main() {
int arr[3][3] = {
{9, 8, 7},
{4, 5, 6},
{1, 2, 3}
};
int rows = sizeof(arr) / sizeof(arr[0]);
int cols = sizeof(arr[0]) / sizeof(arr[0][0]);
Point result = findAvalley(arr, rows, cols);
if (result.row != -1 && result.col != -1) {
printf("找到了鞍点 (%d, %d),数值: %d\n", result.row, result.col, arr[result.row][result.col]);
} else {
printf("未找到鞍点。\n");
}
return 0;
}
```
这个程序首先定义了一个`Point`结构体来存储行和列的位置,然后分别判断元素是否在其所在的行中是最小值,在其所在的列中是最大值。如果找到满足条件的元素,则返回其位置;如果没有找到,最后返回(-1, -1)表示没有鞍点。
阅读全文
相关推荐


















