Implementing DFS traversal using adjacency matrix
Hye! The code terminates after entering values! Can anyone fix it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include<iostream>
using namespace std;
void DFS(int);
int G[10][10], visited[10], n;
void DFS(int i)
{
int j;
cout << i;
visited[i] = 1;
for (j = 0; j < n; j++)
{
if (!visited[j] && G[i][j] == 1)
{
DFS(j);
}
}
}
int main()
{
int i, j;
cout << "Enter number of vertices:" << endl;
cin >> n;
cout << "Enter adjecency matrix of the graph:" << endl;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
cin >> G[i][j];
}
}
for (i = 0; i < n; i++)
{
visited[i] = 0;
DFS(0);
}
system("pasue");
}
|
add
cout.flush()
or
cout<< endl
at line 37.
You need to clear the visited array completely before calling DFS(). So swap lines 35 and 36
When I make these changes and use this input:
4
0 0 1 0
1 1 0 0
0 1 0 1
0 1 0 0 |
I get this output:
Topic archived. No new replies allowed.