-
Notifications
You must be signed in to change notification settings - Fork 2
/
adjacency_matrix.cpp
48 lines (39 loc) · 1 KB
/
adjacency_matrix.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
#include<iostream>
using namespace std;
// Undirected Graph
int main() {
int vertex;
cout << "Enter number of vertex : ";
cin >> vertex;
int edges;
cout << "Enter Number of edges : ";
cin >> edges;
int adjacencyMatrix[vertex][vertex];
for(int i = 0; i < vertex; i++) {
for(int j = 0; j < vertex; j++) {
adjacencyMatrix[i][j] = 0;
}
}
// Enter edges for Undirected Graph
cout << "Enter edges : \n";
for(int i = 0; i < edges; i++) {
int u, v;
cin >> u >> v;
if(u > vertex || v > vertex) {
cout << "Invalid edge!";
i--;
}
else {
adjacencyMatrix[u][v] = 1;
adjacencyMatrix[v][u] = 1; // skip this line for directed graph
}
}
// printing adjacency matrix...
for(int i = 0; i < vertex; i++) {
for(int j = 0; j < vertex; j++) {
cout << adjacencyMatrix[i][j] << " ";
}
cout << "\n";
}
return 0;
}