简体   繁体   中英

Finding a cycle in a graph

I want to write a code for finding a fixed length cycle in a given directed graph which is in adjacency matrix form

bool check(int vertex,int current_vertex, int k, int** graph , int n) {
if (k == 0)
    return (vertex == current_vertex);
for (int i = 0; i < n; i++) {
    if (graph[current_vertex][i] == 1) {
        graph[current_vertex][i] = 0;
        if (check(vertex, i, k - 1, graph, n)) return true;
        graph[vertex][i] = 1;
    }
}
return false;
}

calling the function from main:

    for (int i = 0; i < n; i++) {
        cycle = check(i,i,k,graph,n);
        if (cycle) break;
    }
    cout << (cycle?"TRUE":"FALSE");

my input is given below and there is only one cycle and as expected it is giving true for '5' and false for '1','2','4' but also giving true for '3'. what am i missing?

0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
1 0 0 0 0

I run your code.

You are changing the graph while you are visiting it. This gives you unpredictable results.

When you set the edge as visited you have to set that edge back to its original value.

1) before you return true. In case it found the cycle

2) before going to the next vertex when finishes the loop (you are using vertex instead of current_vertex .

Here is a working implementation of your function.

bool check(int vertex,int current_vertex, int k, int** graph , int n) {
    if (k == 0)
        return (vertex == current_vertex);
    for (int i = 0; i < n; i++) {
        if (graph[current_vertex][i] == 1) {
            graph[current_vertex][i] = 0;
            if (check(vertex, i, k - 1, graph, n)){
                graph[current_vertex][i] = 1;
                return true;
            }
            graph[current_vertex][i] = 1;
        }
    }
    return false;
}

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM