G
G
GeekFromUa2016-01-17 10:34:49
C++ / C#
GeekFromUa, 2016-01-17 10:34:49

How to implement recursive wave algorithm function in c language?

There is a matrix, each element of which is registered as an element of the structure dynamically, with links to neighboring elements as pointers ways (0, 1, 2, 3) - these are directions - up, right, bottom, left, respectively.

typedef struct mapItems{
    int id, xPos, yPos, distance, visited;
    struct mapItem *ways[4];
}mapItem;

I wrote a code that checks neighboring elements and writes the distance there
int wave(mapItem *current, int distance){
    printf(" (%d:%d)b=%d-> ", current->xPos, current->yPos, back);
    int i;
    for(i=0; i<4; i++){
        if((current->ways[i]!=0)&&!(current->ways[i]->visited)){
            if(!current->ways[i]->visited){
                current->ways[i]->distance=distance+1;
            }         
        }  
    }

I can’t figure out how to recurse this function so that it would check in stages, that is, first all the elements with a distance of 1 went around in a circle, then a wave further. I did it, only it goes in one direction. It is necessary to somehow pass the variable inside so that it processes everything around and you can move on. But I can't catch up on how to write it.
Link to the algorithm.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2016-01-17
@petriychuk

Somehow you overdid it, recursion is absolutely not needed here.
To begin with, we create a queue, include the starting point in it.
While the queue is not empty, we take a point from it, write down the length of the path to all its available empty neighbors and put them in the queue. You can interrupt the cycle even earlier, upon reaching the set point.
We restore the path in reverse.

O
Oleg Tsilyurik, 2016-01-17
@Olej

I can't figure out how to recurse this function

You asked a rather difficult question + and even piled up obscene, overly complex structures ...
What did you expect?
To the fact that here in 2 words they will draw a solution to tracing problems for you?
Writing a recursive search takes... a certain amount of habit. You can't explain it in 2 words.
Here you can see: C++ programming tasks - there are several tasks (with solutions - cherepah, etc.) that simply repeat your task, but in a more simplified, lighter formulation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question