I am new to recursion, I am having trouble getting the right solution on how to do recursion on 2D array. Can you please give me idea how to fix my logic on my code. I think my algorithm is not correct.
I tried to create recursion on some point but its not working.
#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();
}
The expected output should be the lowest vertex that is connected to the vertex "testThisVertex" or current vertex. But in my result it ended looping and looping.