-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgraph.h
More file actions
124 lines (96 loc) · 2.81 KB
/
graph.h
File metadata and controls
124 lines (96 loc) · 2.81 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
#define MAX_VERTEX 100
#include <vector>
#pragma once
class Graph{
public :
Graph() ;
void PrintAdjacencyMatrix() ;
void PrintAdjacencyList();
void DjikstraShortestPath(char s);
private :
int V ;
char VertexName[MAX_VERTEX] ;
int AdjacenyWeightedMatrix[MAX_VERTEX][MAX_VERTEX] = {0} ;
std :: vector <std :: vector <int>> AdjacencyList ;
void CreateAdjacencyList() ;
};
Graph :: Graph(){
std :: cin >> V ;
for(int i = 0 ; i < V ; i++){
std :: cin >> VertexName[i] ;
}
for(int i = 0 ; i < V ; i++){
for(int j = 0 ; j < V ; j++){
std :: cin >> AdjacenyWeightedMatrix[i][j] ;
}
}
CreateAdjacencyList() ;
}
void Graph :: PrintAdjacencyMatrix(){
std :: cout << "*| " ;
for(int i = 0 ; i < V ; i++){
std :: cout << VertexName[i] << " ";
}
std :: cout << std :: endl ;
for(int i = 0 ; i < V ; i++){
std :: cout << VertexName[i] << "| " ;
for(int j = 0 ; j < V ; j++){
std :: cout << AdjacenyWeightedMatrix[i][j] << " ";
}
std :: cout << std :: endl ;
}
}
void Graph :: CreateAdjacencyList(){
for(int i = 0 ; i < V ; i++){
std :: vector <int> v ;
for(int j = 0 ; j < V ; j++ ){
if(AdjacenyWeightedMatrix[i][j]){
v.push_back(j) ;
}
}
AdjacencyList.push_back(v) ;
}
}
void Graph :: PrintAdjacencyList(){
for(int i = 0 ; i < V ; i++){
std :: cout << VertexName[i] ;
for(int j = 0 ; j < AdjacencyList[i].size() ; j++){
std :: cout << " -> " << VertexName[AdjacencyList[i][j]] ;
}
std :: cout << std :: endl ;
}
}
void Graph :: DjikstraShortestPath(char s){
int source = -1 ;
for(int i = 0 ; i < V ; i++){
if(s == VertexName[i]){
source = i ;
break ;
}
}
if(source == -1 ){
std :: cout << "NO VERTEX WITH NAME " << s << " EXISTS" << std :: endl ;
return ;
}
int D[V] ;
memset(D,1000000,sizeof(D)) ;
int P[V] ;
memset(P,-1,sizeof(P)) ;
D[source] = 0 ;
std :: priority_queue <std :: pair<int,int>, std :: vector< std :: pair<int,int>>, std :: greater<std :: pair<int,int>>> q;
q.push({D[source],source}) ;
while (!q.empty()){
int p = q.top().second ;
q.pop() ;
for (auto v : AdjacencyList[p]){
if(D[v] > D[p] + AdjacenyWeightedMatrix[p][v]){
D[v] = D[p]+ AdjacenyWeightedMatrix[p][v] ;
P[v] = p ;
q.push({D[v],v}) ;
}
}
}
for(int i = 0 ; i < V ; i++){
std :: cout << VertexName[i] << " " << D[i] << " " << VertexName[P[i]] << std :: endl ;
}
}