Tuesday, 17 February 2026

Graph representation using Adjacensy List using linked list O(1) insertion time And BFS Traversal and DFS traversal

#include <iostream>

#include<bits/stdc++.h>

using namespace std;


// Linked list node

struct Node {

int data;

Node* next;

Node(int value) {

data=value;

next=NULL;

}

};


// Graph

class Graph {

int V;

Node* adj[10];


public:

Graph(int v) {

V = v;


// initialize all lists empty

for (int i = 0; i < V; i++)

adj[i] = NULL;

}


void addEdge(int u, int v) {

// add v to u

Node* n1 = new Node(v);

n1->next=adj[u];


adj[u] = n1;


// add u to v

Node* n2 = new Node(u);

n2->next=adj[v];

adj[v] = n2;

}


void print() {

for (int i = 0; i < V; i++) {

cout << i << ": ";

Node* temp = adj[i];


while (temp != NULL) {

cout << temp->data << " -> ";

temp = temp->next;

}


cout << "NULL\n";

}

}

void BFS() {

queue<int>q;

unordered_map<int,int>um;

//int x = rand() % V;

int x=0;

q.push(x);

um[x]=1;

while(!q.empty()) {

int temp=q.front();

cout<<temp<<" ";


q.pop();

Node* point=adj[temp];

while(point) {

if(!um[point->data]) {

q.push(point->data);

um[point->data]=1;

}

point=point->next;

}


}

}

void DFS(int node,unordered_map<int,int>&visited) {

cout<<node<<" ";

visited[node]=1;

Node*point=adj[node];

while(point) {

if(!visited[point->data]) {

DFS(point->data,visited);

}

point=point->next;

}

}

};


int main() {

Graph g(7);

/* g.addEdge(0,3);

g.addEdge(0,1);

g.addEdge(0,2);

g.addEdge(1,2);

g.addEdge(2,3);

g.addEdge(2,4);

g.addEdge(2,5);

g.addEdge(3,4);

g.addEdge(4,5);*/

g.addEdge(0,1);

g.addEdge(0,3);

g.addEdge(1,2);

g.addEdge(3,4);

g.addEdge(4,5);

g.addEdge(5,6);


unordered_map<int,int>um;



g.print();

cout<<"***********************"<<endl;

g.BFS();

cout<<endl;

cout<<"*******************"<<endl;

g.DFS(0,um);

}

No comments:

Post a Comment

SDE floyd-warshall algorithm

 // User function template for C++ class Solution {   public:     void floydWarshall(vector<vector<int>> &dist) {         //...