Skip to content

Commit ed383ef

Browse files
authored
Create 01 - Adjacency Matrix - Hashmap.cpp
1 parent 4eeca2b commit ed383ef

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <iostream>
2+
#include <unordered_map>
3+
4+
using namespace std;
5+
6+
template <typename T>
7+
class graph{
8+
public:
9+
unordered_map<int, unordered_map<int, int>> adjacencyMatrix;
10+
11+
void addEdge(T source, T destination, int weight = 1, bool isDirected = false){
12+
adjacencyMatrix[source][destination] = weight;
13+
if(!isDirected) adjacencyMatrix[destination][source] = weight;
14+
}
15+
16+
void printMatrix(int totalVertices){
17+
for(int row = 0; row < totalVertices; row++){
18+
for(int col = 0; col < totalVertices; col++){
19+
if (adjacencyMatrix[row].count(col) > 0) {
20+
cout << adjacencyMatrix[row][col] << " ";
21+
}else{
22+
cout << 0 << " ";
23+
}
24+
}
25+
cout << endl;
26+
}
27+
}
28+
29+
};
30+
int main() {
31+
graph<int> g;
32+
33+
int totalVertices = 3;
34+
35+
// Adding edges to the graph
36+
g.addEdge(0, 1, 1, true);
37+
g.addEdge(1, 2, 1, true);
38+
g.addEdge(2, 0, 1, true);
39+
40+
// Printing the adjacency matrix
41+
cout << "Adjacency Matrix:" << endl;
42+
g.printMatrix(totalVertices);
43+
44+
return 0;
45+
}

0 commit comments

Comments
 (0)