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