0% found this document useful (0 votes)
34 views

Graphs DFS

This C++ program implements depth-first search (DFS) on a graph. It takes the number of vertices and edges as input, builds the adjacency matrix, and performs DFS starting from an initial vertex. It uses a stack to keep track of vertices to visit, prints the discovery order, and marks visited vertices to avoid cycles.

Uploaded by

sreeja1992
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Graphs DFS

This C++ program implements depth-first search (DFS) on a graph. It takes the number of vertices and edges as input, builds the adjacency matrix, and performs DFS starting from an initial vertex. It uses a stack to keep track of vertices to visit, prints the discovery order, and marks visited vertices to avoid cycles.

Uploaded by

sreeja1992
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

/* Write C++ programs for the implementation of DFS for a given graph */ #include<iostream> #include<conio.h> #include<stdlib.

h> using namespace std; int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10]; main() { int m; cout <<"enterno of vertices"; cin >> n; cout <<"ente no of edges"; cin >> m; cout <<"\nEDGES \n"; for(k=1;k<=m;k++) { cin >>i>>j; cost[i][j]=1; } cout <<"enter initial vertex"; cin >>v; cout <<"ORDER OF VISITED VERTICES"; cout << v <<" "; visited[v]=1; k=1; while(k<n) { for(j=n;j>=1;j--) if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1) { visit[j]=1; stk[top]=j; top++; } v=stk[--top]; cout<<v << " "; k++; visit[v]=0; visited[v]=1; } }

OUTPUT enterno of vertices9 ente no of edges9 EDGES 12 23 26 15 14 47 57 78 89 enter initial vertex1 ORDER OF VISITED VERTICES1 2 3 6 4 7 8 9 5

You might also like