-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab10_graphs.cpp
More file actions
65 lines (56 loc) · 1.49 KB
/
Lab10_graphs.cpp
File metadata and controls
65 lines (56 loc) · 1.49 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
#include <iostream>
#include<list>
using namespace std;
struct Node{
// A node will 2 entities
//1. data type int called label
//2. a int type list called neighbours
int label;
list<int> neighbours;
};
struct Graph{
//graph will have an array of type "node" with length specified by n
int n=8;
Node * nodes = new Node[n];
void intializenodes(){
//iterate through the nodes and assign labels
for(int i=1;i<=n;i++){
nodes[i].label=i;
}
}
void addedge(int u, int v){
//select node u and push v into u's neighbour
nodes[u - 1].neighbours.push_back(v);
//select node v and push u into v's neighbour
nodes[v - 1].neighbours.push_back(u);
}
void print(){
//lets iterate through each node and print its neighbours
for (int i = 0; i < n; i++) {
cout << nodes[i+1].label << " --> ";
for (int neighbour : nodes[i].neighbours) {
cout << neighbour << " ";
}
cout << endl;
}
}
};
int main() {
Graph * g = new Graph;
g->intializenodes();
//add edges for the graphs here.
g->addedge(1, 2);
g->addedge(1, 3);
g->addedge(1, 4);
g->addedge(1, 5);
g->addedge(2, 3);
g->addedge(2, 6);
g->addedge(4, 6);
g->addedge(4, 7);
g->addedge(4, 8);
g->addedge(5, 6);
g->addedge(5, 7);
g->addedge(5, 8);
//print the graph adjaceny list
g->print();
}