Graph Program

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 3

#include<iostream.

h>

#define MAX 10

class DFS
{
private : int n;
int adj[MAX][MAX];
int visited[MAX];
public : void dfs(int);
void readmatrix();
};

void DFS :: readmatrix()


{
int i,j;
cout << "\nEnter the number of Vertices in the Graph : ";
cin >> n;
cout << "\nEnter the Adjacency Matrix\n\n";
for (i = 1; i <= n; i++)
for (j = 1; j<= n; j++)
cin >> adj[i][j];
for (i = 1; i <= n; i++)
visited[i] = 0;
}

void DFS :: dfs(int source)


{
int i;
visited[source] = 1;
cout << source << " ";
for (i = 1; i <= n; i++)
if (adj[source][i] && !visited[i])
dfs(i);
}

int main()
{
int source;
DFS depth;
depth.readmatrix();
cout << "\nEnter the Source : ";
cin >> source;
cout << "\nThe nodes visited in the DFS order is : ";
depth.dfs(source);
return 0;
}

DFS - source code (cpp)

• Algorithm for general graphs


o DFS starts the search from a starting vertex v0
o When a vertex is reached, it is marked "visited" and the search starts from an
unmarked vetex w that is adjacent from v
o The search continues until a dead-end vertex is reached
 i.e. a vertex whose all adjacent vertices are marked "visited"
o At the dead-end, the algorithm backs up along the last edge traversed and starts
exploring from there.
• Tree is implemented using an adjacency matrix
o space complexity O( V2 )
o edge detection time O(1)
• n nodes will make n calls to DFS()
• All edges are visited exactly once
• Node 0 is the starting point
• the program outputs the original graph followed by all possible DFS trees with its
corresponding component
• Time Complexity of algorithm: Θ( n2 )
• Space Complexity of algorithm: Θ (n)
• Program output
BFS - source code (java)

• Algorithm for general graphs


o Def: i is explored when all nbrs of i are visited.
o Start at a random node i.
o visit all the neighbors of node i.
 add each neighbor visited, but unexplored to a queue
o Now node i is explored.
o Pop the first element off the queue and repeat the process.
• Tree is implemented using an adjacency matrix
• Time Complexity: Θ( n2 )
• Space Complexity: Θ (n)

• Program output

You might also like