search-algorithms/src/algorithm.cpp

109 lines
2.8 KiB
C++

#include "algorithm.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <queue>
Graph ReadInGraph(std::string fileLocation) {
std::cout << fileLocation << std::endl;
std::ifstream graphFile(fileLocation);
if (!graphFile.is_open()) {
std::cerr << "Error opening file, check filename" << std::endl;
exit(1);
}
Graph newGraph;
graphFile >> newGraph.nodeCount;
newGraph.vertices.resize(newGraph.nodeCount + 1);
std::string line;
int source, destination, weight;
while (std::getline(graphFile, line)) {
std::istringstream iss(line);
iss >> source;
do {
iss >> destination >> weight;
newGraph.vertices.at(source).nodeNumber = source;
newGraph.AddEdge(source, destination, weight);
} while (!iss.eof());
}
graphFile.close();
return newGraph;
}
/* Old Node
Node::Node(int destination, int weight) {
this->destination = destination;
this->weight = weight;
}
*/
Graph::Graph(void) {
nodeCount = -1;
}
Edge::Edge(Vertex* destination, int weight) {
this->destination = destination;
this->weight = weight;
}
void Graph::AddEdge(int source, int destination, int weight) {
vertices.at(source).edges.emplace_back(&(vertices.at(destination)), weight);
}
void Graph::PrintGraph(void) {
for (auto i : vertices) {
std::cout << "Source " << i.nodeNumber << " has ";
for (auto j : i.edges) { std::cout << " " << j.destination->nodeNumber; }
std::cout << std::endl;
}
std::cout << std::endl;
}
void PrintSolution(std::vector<Vertex*> solution) {
std::cout << "Path: ";
for (auto i : solution) { std::cout << i->nodeNumber << ' '; }
std::cout << std::endl;
}
std::vector<Vertex*> UCBFS(Graph graph, int start, int end) {
std::vector<Vertex*> solution;
return solution;
}
std::vector<Vertex*> BFS(Graph graph, int start, int end) {
// Setup
std::vector<Vertex*> solution;
std::queue<int> nodeQueue;
nodeQueue.push(start);
// Search
while (!nodeQueue.empty()) {
int currentNode = nodeQueue.front();
solution.push_back(&graph.vertices.at(currentNode));
nodeQueue.pop();
for (auto i : graph.vertices.at(currentNode).edges) {
nodeQueue.push(i.destination->nodeNumber);
}
if (currentNode == end) { return solution; } // Solution found
if (solution.size() > graph.nodeCount) {
std::cout << "Path too long" << std::endl;
break;
}
}
solution.clear();
solution.push_back(&graph.vertices.at(0));
return solution;
}
std::vector<Vertex*> DFS(Graph graph, int start, int end) {
std::vector<Vertex*> solution;
return solution;
}