![](/img/trans.png)
[英]Find a value within a multidimensional array that is closest to a given value in Embedded C
[英]Find max value in multidimensional array recursively
我正在研究一种算法,以递归方式查找多维数组(任意大小)中的最大值。 但它不能正常工作。
#include <stdio.h>
int N = 5;
int maxInRow(int matrix[][N], int row, int cols)
{
if (cols == 0){
return matrix[row][cols];
}
int maxCandidate = matrix[row][cols - 1];
int maxSublist = maxInRow(matrix, row, cols - 1);
int max = (maxSublist > maxCandidate) ? maxSublist : maxCandidate;
return max;
}
int main()
{
int mtx[5][5] = {{8,1,2,6,7}, {1,80,3,9,6}, {4,5,5,1,8}, {1,2,3,4,5}, {5,4,3,5,300}};
printf("%d\n", maxInRow(mtx, 1, N-1));
}
它应该返回 300,但它返回 80。我哪里出错了?
你所做的是找出特定行的最大值,而不是多维 arrays 的最大值。要获得整个 arrays 的最大值,需要递归比较所有行的所有项目。
这是实现这一目标的方法之一(下面的代码)
#include <stdio.h>
int N = 5;
int maxInRow(int matrix[][N], int row, int cols)
{
if (cols == 0 ){
if(row==1) {
// the last element of the matrix
return matrix[0][0];
}
else{
// Comparing all items of row is done, begin next row
row--;
cols=N;
}
}
int maxCandidate = matrix[row-1][cols - 1];
int maxSublist = maxInRow(matrix, row, cols - 1);
int max = (maxSublist > maxCandidate) ? maxSublist : maxCandidate;
return max;
}
int main()
{
int mtx[5][5] = {{8,1,2,6,7}, {1,80,3,9,6}, {4,5,5,1,8}, {1,2,3,4,5}, {5,4,3,5,300}};
printf("%d\n", maxInRow(mtx, N, N));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.