Can anybody give me a C Code to find all possible paths between two nodes? eg. if the graph has following edges 1-2 1-3 2-3 2-4 3-4
all paths between 1 and 4 are:
1-2-3-4
1-2-4
1-3-4
1-3-2-4
Can anybody give me a C Code to find all possible paths between two nodes? eg. if the graph has following edges 1-2 1-3 2-3 2-4 3-4
all paths between 1 and 4 are:
1-2-3-4
1-2-4
1-3-4
1-3-2-4
(I'm assuming you don't want repeated nodes in your path - otherwise the number of possible paths is infinite.)
You can do a relaxation:
while (there is a change) {
for (v in nodes(G)) {
for (e in edges(v)) {
paths_to[v] = paths_to[v] union ((paths_to[e.to] not containing v) append v)
}
}
}
The result can still be exponential in the size of the input graph. Getting all paths is probably not what you want to do.
This is a simple algorithm to the problem. It is not an optimal algorithm.
static struct {
int value1;
int value2;
int used;
} data[] = {
{ 1, 2 },
{ 1, 3 },
{ 2, 3 },
{ 2, 4 },
{ 3, 4 },
};
enum { DATA_SIZE = sizeof data / sizeof *data };
static int output[DATA_SIZE];
int traverse(int from, int to, int depth) {
output[depth++] = from;
int i;
if (from == to) {
for (i = 0; i < depth; i++) {
if (i) {
printf("-");
}
printf("%d", output[i]);
}
printf("\n");
} else {
for (i = 0; i < DATA_SIZE; i++) {
if (!data[i].used) {
data[i].used = 1;
if (from == data[i].value1) {
traverse(data[i].value2, to, depth);
} else if (from == data[i].value2) {
traverse(data[i].value1, to, depth);
}
data[i].used = 0;
}
}
}
}
int main() {
traverse(1, 4, 0);
}
a recursive method:
findPaths(path = startNode, goal)
paths = []
if the last node in path is goal:
return path
for each node n connected to the last node in path:
if n is not already on the path:
paths.append(findPaths(path.append(node), goal))
return paths //may still be []
hi bkail, thanks for your program.but i am finding some difficulties while checking for the following nodes,too many cycles are coming.
can you try the following edges and find path having no repeated nodes between 1 and 4
{0, 5}, {1 ,4}, {0, 2}, {5 ,4 }, {1 ,2 }, {4 ,3 }, {3 ,10}, {1, 6 }, {6 ,2 }, {2 ,3 }, {2, 7 }, {3 ,14 }, {6, 7 }, {7, 8 }, {8, 10 }, {8, 9 }, {8 ,12 }, {8 ,14}, {5 ,11 }, {10 ,11 }, {10 ,13}, {10 ,9 }, {11 ,14 }, {11 ,12 }, {12 ,13 }, {13 ,14 },