in c++ You are to implement a straightforward application of Depth First Search
ID: 3828507 • Letter: I
Question
in c++
Explanation / Answer
#include <iostream>
#include <list>
#include <fstream>
using namespace std;
int a[20][20], visited[20], n, i, j;
void dfs(int v)
{
int j;
visited[v]=1;
for(j=1; j<=n; j++)
if(!visited[j]&&a[v][j])
dfs(j);
}
int main()
{
int v;
FILE *file = fopen("data.txt","r");
fscanf(file, "%d" , &n);
// Read the data into the matrix
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
fscanf(file, " %d", &a[i][j] );
}
}
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
if(a[i][i] != 0)
{
cout << "The diagonal elements of the matrix are not 0" << endl;
return 0;
}
else if(!(a[j][i]==a[i][j]&& i==j))
{
cout << "The given matrix is not Symmetric Matrix "<<endl;
return 0;
}
}
}
fscanf(file, "%d" , &v);
dfs(v);
cout << "The nodes which are reachable are from " << v << " : ";
for(i=1; i<=n; i++)
{
if(visited[i])
cout << i << endl;
}
return 0;
}
data.txt
5
0 1 0 1 0
0 0 0 1 1
1 0 0 1 0
0 0 0 0 1
0 0 0 0 0
1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.