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

Graphs Trees Algorithms

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)
6 views

Graphs Trees Algorithms

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/ 11

Data Structure & Algorithms

Graphs Programs
Depth First Search of Graph
// C++ program to print DFS traversal from a given vertex in a given graph
#include <bits/stdc++.h>
#include<iostream>
using namespace std;

// Graph class represents a directed graph using adjacency list representation


class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;

// function to add an edge to graph


void addEdge(int v, int w);

// DFS traversal of the vertices


// reachable from v
void DFS(int v);
};

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


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::DFS(int v)
{
// Mark the current node as visited and print it
visited[v] = true;
cout << v << " ";

// Recur for all the vertices adjacent


// to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}
int main()
{
// Create a graph given in the above diagram
Input: n = 4, e = 6
0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3
Output: DFS from vertex 1 : 1 2 0 3
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Depth First Traversal"


" (starting from vertex 2) \n";

// Function call
g.DFS(2);

return 0;
}
Depth First Search of Graph
//Program to print BFS traversal from a given source vertex. BFS(int s) traverses vertices
reachable from s.
#include<bits/stdc++.h>
using namespace std;

// This class represents a directed graph using adjacency list representation


class Graph
{
int V; // No. of vertices

// Pointer to an array containing adjacency lists


vector<list<int>> adj;
public:
Graph(int V); // Constructor

// function to add an edge to graph


void addEdge(int v, int w);

// prints BFS traversal from a given source s


void BFS(int s);
};

Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}

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


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::BFS(int s)
{
// Mark all the vertices as not visited
vector<bool> visited;
visited.resize(V,false);

// Create a queue for BFS


list<int> queue;

// Mark the current node as visited and enqueue it


visited[s] = true;
queue.push_back(s);

while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();

// Get all adjacent vertices of the dequeued


// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (auto adjecent: adj[s])
{
if (!visited[adjecent])
{
visited[adjecent] = true;
queue.push_back(adjecent);
}
}
}
}

int main()
{

// Create a graph given in the above diagram


Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Breadth First Traversal "


<< "(starting from vertex 2) \n";
g.BFS(2);

return 0;
}

Trees Programs
// Tree traversal in C++

#include <iostream>
using namespace std;

struct Node {
int data;
struct Node *left, *right;
Node(int data) {
this->data = data;
left = right = NULL;
}
};
// Preorder traversal
void preorderTraversal(struct Node* node) {
if (node == NULL)
return;

cout << node->data << "->";


preorderTraversal(node->left);
preorderTraversal(node->right);
}

// Postorder traversal
void postorderTraversal(struct Node* node) {
if (node == NULL)
return;

postorderTraversal(node->left);
postorderTraversal(node->right);
cout << node->data << "->";
}

// Inorder traversal
void inorderTraversal(struct Node* node) {
if (node == NULL)
return;

inorderTraversal(node->left);
cout << node->data << "->";
inorderTraversal(node->right);
}

int main()
{
struct Node* root = new Node(1);
root->left = new Node(12);
root->right = new Node(9);
root->left->left = new Node(5);
root->left->right = new Node(6);

cout << "Inorder traversal ";


inorderTraversal(root);

cout << "\nPreorder traversal ";


preorderTraversal(root);
cout << "\nPostorder traversal ";
postorderTraversal(root);
return 0;
}

Heaps Programs
// A C++ program to demonstrate common Binary Heap Operations
#include<iostream>
#include<climits>
using namespace std;

// Prototype of a utility function to swap two integers


void swap(int *x, int *y);

// A class for Min Heap


class MinHeap
{
int *harr; // pointer to array of elements in heap
int capacity; // maximum possible size of min heap
int heap_size; // Current number of elements in min heap
public:
// Constructor
MinHeap(int capacity);

// to heapify a subtree with the root at given index


void MinHeapify(int );

int parent(int i) { return (i-1)/2; }


// to get index of left child of node at index i
int left(int i) { return (2*i + 1); }

// to get index of right child of node at index i


int right(int i) { return (2*i + 2); }

// to extract the root which is the minimum element


int extractMin();

// Decreases key value of key at index i to new_val


void decreaseKey(int i, int new_val);

// Returns the minimum key (key at root) from min heap


int getMin() { return harr[0]; }

// Deletes a key stored at index i


void deleteKey(int i);

// Inserts a new key 'k'


void insertKey(int k);
};

// Constructor: Builds a heap from a given array a[] of given size


MinHeap::MinHeap(int cap)
{
heap_size = 0;
capacity = cap;
harr = new int[cap];
}

// Inserts a new key 'k'


void MinHeap::insertKey(int k)
{
if (heap_size == capacity)
{
cout << "\nOverflow: Could not insertKey\n";
return;
}

// First insert the new key at the end


heap_size++;
int i = heap_size - 1;
harr[i] = k;

// Fix the min heap property if it is violated


while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}

// Decreases value of key at index 'i' to new_val. It is assumed that


// new_val is smaller than harr[i].
void MinHeap::decreaseKey(int i, int new_val)
{
harr[i] = new_val;
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}

// Method to remove minimum element (or root) from min heap


int MinHeap::extractMin()
{
if (heap_size <= 0)
return INT_MAX;
if (heap_size == 1)
{
heap_size--;
return harr[0];
}

// Store the minimum value, and remove it from heap


int root = harr[0];
harr[0] = harr[heap_size-1];
heap_size--;
MinHeapify(0);

return root;
}
// This function deletes key at index i. It first reduced value to minus
// infinite, then calls extractMin()
void MinHeap::deleteKey(int i)
{
decreaseKey(i, INT_MIN);
extractMin();
}

// A recursive method to heapify a subtree with the root at given index


// This method assumes that the subtrees are already heapified
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i])
smallest = l;
if (r < heap_size && harr[r] < harr[smallest])
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
// A utility function to swap two elements
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

// Driver program to test above functions


int main()
{
MinHeap h(11);
h.insertKey(3);
h.insertKey(2);
h.deleteKey(1);
h.insertKey(15);
h.insertKey(5);
h.insertKey(4);
h.insertKey(45);
cout << h.extractMin() << " ";
cout << h.getMin() << " ";
h.decreaseKey(2, 1);
cout << h.getMin();
return 0;
}

You might also like