Search code examples
c++depth-first-search

How can I back up to an earlier value in Depth-First Search c++?


Here, I'm implementing Depth-First Search (DFS) in c++. However, I can't seem to find a way to back up to the previous place (i.e. 1->2->3 if 3 is end of line go back to 2)

Can I use vectors or stacks to track my movements?

int searcher(int line[3], int lineNumber) {
    int value = 0;
    if (line[0] == 1) {
        if (hasRunLine[lineNumber+1] != 1) {
            value = lineNumber + 1;
        } else {
            value = -1; // here it needs to go back and check whether it is at the start
        }
    } else if (line[0] = 2) {
        if (hasRunLine[line[1]] != 1) {
            value = line[1];
        } else {
            value = -1; // here too
        }
    } else {
        if (hasRunLine[line[1]] != 1) {
            value = line[1];
        } else if (hasRunLine[line[2]] != 1) {
            value = line[2];
        } else {
            value = -1; // here too
        }
    }
    if (value <= maximum && value >= 2) {
        return value;
    } else {
        return -1; // here too
    }
}

Solution

  • Use a vector and add a new movement everytime you switch to a different position.