-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjecencyList.cpp
More file actions
146 lines (125 loc) · 2.15 KB
/
AdjecencyList.cpp
File metadata and controls
146 lines (125 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
/*
//array and can be done with lists
class Graph{
public:
Graph(int v){
V=v;
array.resize(V);
}
void addEdge(int src, int dest){
array[src].push_back(dest);
}
void display(){
for(int i=0; i<array.size(); i++){
cout<<"for vertex: "<<i;
cout<<" head-> ";
for(int j=0; j<array[i].size(); j++){
cout<<array[i][j]<<" ";
}
cout<<endl;
}
}
private:
int V;
vector< vector<int>> array;
};
*/
class GraphN{
public:
struct Node{
int data;
Node *next;
};
struct Adjlist{
Node *head;
};
GraphN(int vertex){
V=vertex;
arr = new Adjlist[V];
for(auto i=0; i<V; i++){
arr[i].head = NULL;
}
}
void addEdge(int src, int dest){
Node *temp =new Node();
temp->data = dest;
temp->next=arr[src].head;
arr[src].head=temp;
Node *temp1 =new Node();
temp1->data =src;
temp1->next=arr[dest].head;
arr[dest].head=temp1;
}
void DFS(){
vector <bool>visited(V, false);
stack <int> s;
Node *temp;
s.push(0);
visited[0] = true;
cout<<"visited virtex : "<<0;
while(!s.empty()){
int k=s.top();
s.pop();
temp = arr[k].head;
while(temp!=NULL){
if(!visited[temp->data]){
s.push(temp->data);
visited[temp->data]=true;
cout<<" -> "<<temp->data;
}
temp =temp->next;
}
}
}
void BFS(){
vector<bool> visited(V, false);
queue <int> q;
visited[0]=true;
q.push(0);
int el;
Node *temp;
while(!q.empty()){
el = q.front();
cout<<el<<" ";
q.pop();
temp=arr[el].head;
while(temp!=NULL){
if(!visited[temp->data]){
visited[temp->data]=true;
q.push(temp->data);
}
temp=temp->next;
}
}
}
void display(){
for(auto i=0; i<V; i++){
Node *temp = arr[i].head;
cout<<"Adjecency list for vectex: "<<i<<" head";
while(temp!=NULL){
cout<<" -> "<<temp->data;
temp=temp->next;
}
cout<<endl;
}
}
private:
int V;
struct Adjlist* arr;
};
int main(){
GraphN g(6);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
g.addEdge(2, 5);
// g.display();
g.DFS();
return 0;
}