input v = 4, e =3
edges (1,2)
edges (3,2)
edges (3,1)
i want to check u = 3, v = 1
out put: yes and i want check u = 1, v = 3
out put: no
have matrix
0 1 0 0
0 0 0 0
1 1 0 0
0 0 0 0
void DFS(int i,int t)
{
int j;
visited[i] = 1;
cout << i+1 << " ";
if(i == t)
cout << "yes";
for(j=0;j<V;j++)
{
if(G[i][j]==1 && visited[j] == 0)
DFS(j,t,x);
}
}
Normally a DFS implementation for something like this might look something like (I haven't tested it so there may be an issue or two):
bool dfs(int this_node, int destination_node) {
// base case where this node is the destination node
if (this_node == destination_node) return true;
// mark this node as visited
visited[this_node] = true;
// go deeper in the search
for (size_t next_node = 0; next_node < V; ++ next_node) {
// skip the search if this node isn't a valid child
if (visited[next_node] || !g[this_node][next_node]) {
continue;
}
// here is the recursive step
if (dfs(next_node, destination_node)) {
return true;
}
}
// if we made it all the way here, then the search failed to reach the destination
return false;
}
Then you'd be able to call this from the main function:
if (dfs(source_node, destination_node)) {
std::cout << "yes\n";
} else {
std::cout << "no\n";
}
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.