求二维数组的鞍点(C++)

本文介绍了如何在C++中找到二维数组的鞍点,即某元素既是其所在行的最大值,又是其所在列的最小值。通过`maxToLine`函数找出每行的最大值的列索引,然后使用`isMaxColumn`函数验证该值是否为列的最小值。示例代码展示了如何遍历数组并打印出所有鞍点。
摘要由CSDN通过智能技术生成

题目说明:

二维数组的鞍点,即对于一个整数数组中(或其他数组)的某一位置的值即是这一行的最大值又是这一列的最小值。

当然,只有特定的数组存在鞍点,请尝试查找一个满足条件的整形数组的鞍点。

代码实现:

#include <iostream>
using namespace std;

#define N 3
#define M 5
int s[N][M]={
        {1,2,3,4,5},
        {6,7,8,9,10},
        {11,12,13,14,15}
};

// 输入指定行的索引,返回一行中最大值的列索引
int maxToLine(int line)
{
    int cIndex = 0,temp = s[line][0];
    for (int j = 0; j < M; ++j)
    {
        if(s[line][j] > temp)
        {
            temp = s[line][j];
            cIndex = j;
        }
    }
    return cIndex;
}

// 输入行索引line和列索引column,判断索引指向的值是否是数组中column列的最小值
// 是则返回true,否则返回false
bool isMaxColumn(int line,int column)
{
    int sumMax = s[line][column];
    for (int i = 0; i < N; ++i)
    {
        if(s[i][column] < sumMax && i != line)
            return false;
    }
    return true;
}

int main()
{
    for (int i = 0; i < N; ++i)
    {
        int j = maxToLine(i);
        if(isMaxColumn(i,j ))
            cout << s[i][j] << endl;
    }
    return 0;
}

运行结果:

5
C++中,二维数组的“鞍点”指的是数组中某个元素既不是最大值也不是最小值,而是大于它左边的元素小于右边的元素。为了使用指针实现这个功能,可以编写一个函数,遍历整个数组并比较相邻的元素。以下是简单的实现步骤: 1. 定义一个函数,接收二维数组和其行数、列数作为参数,假设二维数组名为 `matrix`,行数为 `rows`,列数为 `cols`: ```cpp struct Point { int row; int col; }; Point findLowestPeak(int matrix[rows][cols], int rows, int cols) { Point result; bool found = false; // 初始化最低点候选点为第一行第一个元素 Point current = {0, 0}; while (!found) { // 比较当前点与其上下左右四个邻居 if (current.row > 0 && matrix[current.row - 1][current.col] > matrix[current.row][current.col]) { continue; // 左边元素较大,继续向下移动 } if (current.row < rows - 1 && matrix[current.row + 1][current.col] < matrix[current.row][current.col]) { continue; // 右边元素较小,继续向右移动 } if (current.col > 0 && matrix[current.row][current.col - 1] > matrix[current.row][current.col]) { continue; // 上方元素较大,继续向左移动 } if (current.col < cols - 1 && matrix[current.row][current.col + 1] < matrix[current.row][current.col]) { // 找到了鞍点,返回当前位置 result.row = current.row; result.col = current.col; found = true; } else { // 向下右方向移动 current.row++; current.col++; } } return result; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值