-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.cpp
99 lines (97 loc) · 2.42 KB
/
graph.cpp
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
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
class Graph
{
public:
int size;
vector<vector<int>> adjMatrix;
Graph(int size)
{
this->size = size;
adjMatrix.resize(size, vector<int>(size));
};
void addEdge(int node1, int node2)
{
if (node1 > size && node2 > size)
{
cout << "Out of range";
return;
}
adjMatrix[node1][node2] = 1;
adjMatrix[node2][node1] = 1;
}
void printAdjacencyMatrix()
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
}
void bfsTraversal(int startNode)
{
vector<bool> visited;
visited.resize(size, false);
queue<int> q;
visited[startNode] = true;
q.push(startNode);
int currentNode;
while (!q.empty())
{
currentNode = q.front();
cout << currentNode << " ";
q.pop();
for (int endNode = 0; endNode < adjMatrix[currentNode].size(); endNode++)
{
if (adjMatrix[currentNode][endNode] == 0)
continue;
int adjacent = endNode;
if (!visited[adjacent])
{
visited[adjacent] = true;
q.push(adjacent);
}
}
}
}
void dfsTraversal(int node)
{
static vector<bool> visited;
visited.resize(size, false);
visited[node] = true;
cout << node << " ";
for (int endNode = 0; endNode < adjMatrix[node].size(); endNode++)
{
if (adjMatrix[node][endNode] == 1 && !visited[endNode])
{
dfsTraversal(endNode);
}
}
}
};
int main()
{
Graph g(7);
g.addEdge(1, 5);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(3, 4);
g.addEdge(4, 5);
g.addEdge(4, 6);
g.addEdge(2, 6);
cout << "Adjacency matrix: " << endl;
g.printAdjacencyMatrix();
cout << "BFS traversal: " << endl;
g.bfsTraversal(1);
cout << endl
<< "DFS traversal: " << endl;
g.dfsTraversal(1);
return 0;
}