【发布时间】:2019-06-04 03:18:59
【问题描述】:
我是递归新手,我无法找到关于如何在二维数组上进行递归的正确解决方案。你能告诉我如何在我的代码上修复我的逻辑吗?我认为我的算法不正确。
我试图在某些时候创建递归,但它不起作用。
#include <stdio.h>
#define HEIGHT 21
#define WIDTH 5
int getLowestVertex(int graph[HEIGHT][WIDTH], int currLabel,int height, int width, int labelCount){
int counter = 0;
int low_label = 999;
int j;
int i;
int *visitedLabelCheck = NULL; //This will identify the visted label already
visitedLabelCheck = (int *)malloc(labelCount * sizeof(int));
//set all value to 0
for(i = 0; i < labelCount; i++){
visitedLabelCheck[i] = 0;
}
printf("\n");
low_label = lowest_label(graph, currLabel, visitedLabelCheck, low_label);
return low_label;
}
int lowest_label(int link[HEIGHT][WIDTH], int currentLabel, int *visitedLabelCheck, int low_label){
int currentCounter = 0;
int lowestLabel = 0;
while(1) {//loop for the current label vertices
if(link[currentLabel][currentCounter] != 0){
if(visitedLabelCheck[currentLabel] == -1)
return link[currentLabel][currentCounter];
if (link[currentLabel][currentCounter] < low_label) {
low_label = link[currentLabel][currentCounter];
}
lowestLabel = lowest_label(link, link[currentLabel][currentCounter], visitedLabelCheck, lowestLabel);
visitedLabelCheck[currentLabel] = -1;
if (lowestLabel < low_label){
return link[currentLabel][currentCounter];
}
currentCounter++;
}else{
break;
}
}
}
int main(int argc, char *argv[]) {
int testThisVertex;
int lowestVertex;
int labelCount;
int height;
int width;
int g[HEIGHT][WIDTH] = {{1, 21, 0, 0, 0}, //undirected graph
{2, 0, 0, 0, 0},
{3, 0, 0, 0, 0},
{4, 5, 0, 0, 0},
{5, 4, 0, 0, 0},
{6, 21, 0, 0, 0},
{7, 8,2, 14, 0},
{8, 7, 9, 0, 0},
{9, 8,10, 0, 0},
{10, 9,11, 0, 0},
{11,10, 0, 0, 0},
{12,13, 0, 0, 0},
{13,12,14, 0, 0},
{14,13,15, 7, 0},
{15,14, 0, 0, 0},
{16, 0, 0, 0, 0},
{17, 0, 0, 0, 0},
{18, 0, 0, 0, 0},
{19,20, 0, 0, 0},
{20,19, 0, 0, 0},
{21,17,18, 6, 1}};
//find the least label if input is 12
//12 -> 13
// | \
// 12 14
// | \ \
// 13 15 7
// | | \ \
// 14 8 2 14
//ANSWER: 2
testThisVertex=12;
labelCount = 21;
height = 21;
width = 5;
lowestVertex = getLowestVertex(g, testThisVertex, height, width, labelCount);
printf("\nThe lowest value that is connected to %d vertex is %d", testThisVertex, lowestVertex);
getchar();
}
预期的输出应该是连接到顶点“testThisVertex”或当前顶点的最低顶点。但在我的结果中,它结束了循环和循环。
【问题讨论】:
-
int graph[HEIGHT][WIDTH]是一个二维数组,它不是一个int **link指针数组。这是个很大的差异。编译器应该警告你。graph[a][b]等于*(graph + a * WIDTH + b)而link[a][b]等于*(*(link + a) + b) -
对不起,我再次编辑了函数更改为链接[HEIGHT][WIDTH]
-
请不要破坏您的帖子。通过在 Stack Overflow 上发帖,您已授予 SO 在 CC BY-SA 3.0 license 下分发该内容的不可撤销权利。根据 SO 政策,任何破坏行为都将被撤销。
标签: c recursion multidimensional-array connected-components