Currently trying to implement dijkstra's algorithm in C++ by the use of an adjacency list in a text file read into a map object. The map is initialized as:
map<int, vector<pair<int, int>>> = adjList;
Sample text file input:
1 2,1 8,2
2 1,1 3,1
3 2,1 4,1
4 3,1 5,1
5 4,1 6,1
6 5,1 7,1
7 6,1 8,1
8 7,1 1,2
Where the key is a vertex, and the x values of the pairs in the vector are connected to the key vertex. The y values are the path distances. I pass that map into my dijkstra function, where I initialize a vector for shortest distances and a vector for storing visited vertices. My loop is where things start going wrong, as I get outputs of zeroes and very large numbers. Here's my code:
//checks if vertex has been visited or not
bool booler(int vertex, vector<int> visited){
bool booly;
if(find(visited.begin(), visited.end(), vertex) != visited.end()){
booly = true;
}
else{
booly = false;
}
return booly;
}
//checks vector for the shortest distance vertex
int minDist(vector<int> distances, vector<int> visited){
int minDist = 1000000;
int index;
for(int v = 0; v < distances.size(); v++){
if(booler(v, visited) == false && distances[v] < minDist){
minDist = distances[v];
index = v;
}
}
return index;
}
void dijkstra(int source, map<int, vector<pair<int, int>>> adjList, int vSize){
vector<int> distances(vSize, 1000000);
vector<int> visited = {};
distances[source] = 0;
for(int c = 0; c < distances.size(); c++){
int u = minDist(distances, visited);
visited.push_back(u);
for(int v = 1; v < distances.size(); v++){
for(int s = 0; s < adjList[u].size(); s++){
//updates distances based on v connection to u
if(booler(v, visited) == false && distances[u] < 1000000 && adjList[u][s].second + distances[u] < distances[v]){
distances[v] = distances[u] + adjList[u][v].second;
}
}
}
}
//prints out shortest path
for(int x = 0; x < distances.size(); x++){
cout << distances[x] << " " << endl;
}
}
I haven't been able to fix this error, any help would be greatly appreciated!