在2D矩阵中查找最大值(递归)

时间:2016-03-02 16:47:46

标签: c recursion matrix

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

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

1 个答案:

答案 0 :(得分:1)

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

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