查找二维矩阵中的最大值(递归) [英] Find the maximum value in a 2D matrix (recursively)

查看:56
本文介绍了查找二维矩阵中的最大值(递归)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力在我的代码中找到错误,我试图在我的 2D 矩阵中的某一行中找到最大值.你能帮我找出我的逻辑失败的地方吗?

I'm struggling to find the error in my code, I'm trying to find the maximum value in my 2D matrix, in a certain row. Can you help me locate where my logic fails?

int maxInRowmaxInRow(int mtx[][N], int row, int cols);
int main()
{
    int mtx[][N] = { {8,1,2,6,7},{1,8,3,9,6},{4,5,-5,1,8},{1,2,3,4,5},{5,4,3,5,3} };
    printf("%d", maxInRow(mtx, 1,N));
    getch();
}

int maxInRow(int mtx[][N], int row, int cols)
{
    int possibleMax = maxInRow(mtx, row, cols - 1);
    if (cols == 0) return mtx[row][cols];

    int max = mtx[row][cols - 1];
    max = (max < maxInRow(mtx, row, cols - 1)) ? possibleMax : max;
    return max;
}

推荐答案

您正在以错误的顺序执行递归终止案例.你也做了两次递归而不是一次.简化您的代码:

You're doing the recursion termination case in the wrong order. You're also do two recursions instead of one. Simplifying your code:

int maxInRow(int mtx[][N], int row, int cols)
{
    if (cols == 0) return mtx[row][cols];

    int possibleMax = mtx[row][cols - 1];

    int sublistMax = maxInRow(mtx, row, cols - 1);

    int max = (sublistMax > possibleMax) ? sublistMax : possibleMax;

    return max;
}

int main()
{
    int mtx[][N] = {{8,1,2,6,7}, {1,8,3,9,6}, {4,5,-5,1,8}, {1,2,3,4,5}, {5,4,3,5,3}};

    printf("%d\n", maxInRow(mtx, 1, N));
}

这篇关于查找二维矩阵中的最大值(递归)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆