In this problem, there are 2 ways: BFS or DFS.
Hawstein used BFS:
#include
#include
#include
#include
using namespace std;
const int maxn = 100;
bool g[maxn][maxn], visited[maxn];
int n;
queue q;
void init(){
memset(g, false, sizeof(g));
memset(visited, false, sizeof(visited));
}
bool route(int src, int dst){
q.push(src);
visited[src] = true;
while(!q.empty()){
int t = q.front();
q.pop();
if(t == dst) return true;
for(int i=0; i>n>>m;
for(int i=0; i>u>>v;
g[u][v] = true;
if(i==0){cout<< "start of connections--" << endl;}
cout<"<
input:
8 11
0 1
1 0
1 5
2 3
2 4
4 7
5 2
5 7
6 2
6 4
7 4
Output:
start of connections-
0->1
1->0
1->5
2->3
2->4
4->7
5->2
5->7
6->2
6->4
7->4
end of connections--
1
1
0
1
Here is the DFS solution but have errors in somecases, such as 0->3. The reason is that the case for v[i] didn't considered visited condition, then go to return false directly.
/*Given a directed graph, design an algorithm to find out whether there is a route between two nodes
*/
#include
#define N 8
using namespace std;
int nextNbr(int g[][N], int i, int j){
while((-1"<"<output:
1st case: 1
0: 0
1: 1
2: 0
3: 0
4: 0
5: 1
6: 0
7: 0
0
0: 0
1: 1
2: 0
3: 0
4: 1
5: 1
6: 0
7: 1
After I learned from zyli's code, The problem is fixed.
The reason is that the previous one fall into narrow path without go back so failed in some corner cases: for example: 0->3
Here is the final version of DFS with recursion.
/*Given a directed graph, design an algorithm to find out whether there is a route between two nodes
*/
#include
#define N 8
using namespace std;
int nextNbr(int g[][N], int i, int j){
while((-1"<"<J: 0, tim: 3
v[0]=0
v[2]=0
J: 1, tim: 5
v[5]=0
J: 1, tim: 5
v[1]=0
J: 1, tim: 5
1
Here is the sample analysis of the recursion for routeDFS(0,3)=1
