c - 查找二维矩阵中的最大值(递归)

标签 c recursion matrix

我正在努力查找代码中的错误,我正在尝试查找二维矩阵中某一行的最大值。你能帮我找到我的逻辑失败的地方吗?

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;
}

最佳答案

您以错误的顺序执行递归终止情况。您还可以执行两次递归而不是一次。简化您的代码:

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));
}

关于c - 查找二维矩阵中的最大值(递归),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35753296/

相关文章:

c - 基本的 C 指针和按引用传递的混淆

比较来自 2 个数组中任何元素的单词

c - 使用在其他源文件中初始化的函数指针

c++ - 如何将此嵌套迭代转换为递归解决方案?

algorithm - 提出树遍历递归算法的分步方法?

python - Numpy:旋转 M 的子矩阵 m

r - 如何让对角线和反对角线穿过二维矩阵中的点?

c - 错误检查,寻求一些指导

algorithm - 最长递增子序列递归解中的一维内存

java - 矩阵乘法/加法的并发