0% found this document useful (0 votes)
7 views3 pages

DSA10 W Name

Dsa stacks

Uploaded by

o.p.ronak2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

DSA10 W Name

Dsa stacks

Uploaded by

o.p.ronak2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Name: Ronak Mishra

Div-B(48)

Experiment no : 10

#include <iostream>

#include <vector>

#include <stack>

#include <queue>

using namespace std;

class Graph { int V;

vector<int> *adj; public:

Graph(int V); void

addEdge(int v, int w); void

DFS(int v); void BFS(int v);

};

Graph::Graph(int V) { this-

>V = V; adj = new

vector<int>[V];

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

adj[w].push_back(v);

void Graph::DFS(int v) {

vector<bool> visited(V,

false); stack<int> s;

s.push(v); while

(!s.empty()) { v =

s.top();

s.pop(); if

(!visited[v]) {

cout << v << " ";

visited[v] = true;
}

for (auto i = adj[v].rbegin(); i != adj[v].rend(); ++i) { if

(!visited[*i]) {

s.push(*i);

void Graph::BFS(int v) {

vector<bool> visited(V,

false); queue<int> q;

visited[v] = true;

q.push(v); while

(!q.empty()) { v =

q.front(); cout << v

<< " ";

q.pop(); for (int i :

adj[v]) { if

(!visited[i]) {

visited[i] = true;

q.push(i);

int main() { Graph

g(5);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 3);

g.addEdge(2, 4); cout << "Depth First Traversal (starting

from vertex 0): ";

g.DFS(0); cout << "\nBreadth First Traversal (starting from

vertex 0): ";

g.BFS(0);

return 0;
}

OUTPUT:

0 -- 1

||

2 -- 4

Depth First Traversal (starting from vertex 0): 0 2 4 1 3

Breadth First Traversal (starting from vertex 0): 0 1 2 3 4

You might also like