Skip to content
Permalink
3926ba983b
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
71 lines (68 sloc) 2.05 KB
#include "weightedGraph.h"
WeightedGraph::WeightedGraph(const int &numberOfNodes) {
for (int i = 0; i < numberOfNodes; i++) {
std::vector<int> row;
for (int j = 0; j < numberOfNodes; j++) {
row.emplace_back(0);
}
connections.emplace_back(row);
}
}
void WeightedGraph::connectNodes(const int &node1, const int &node2, const int &weight) {
if (node2 < node1) {
const int temp = node1;
const int node1 = node2;
const int node2 = temp;
}
if ((node1 < 1) || (node2 > connections.size())) {
throw "Node number is bigger than number of nodes or smaller than 1.";
}
connections[node1 - 1][node2 - 1] = weight;
}
void WeightedGraph::disconnectNodes(const int &node1, const int &node2) {
if (node2 < node1) {
const int temp = node1;
const int node1 = node2;
const int node2 = temp;
}
if ((node1 < 1) || (node2 > connections.size())) {
throw "Node number is bigger than number of nodes or smaller than 1.";
}
connections[node1 - 1][node2 - 1] = 0;
}
void WeightedGraph::printAdjacencyMatrix() {
for (int i = 0; i < connections.size(); i++) {
for (int j = 0; j < connections.size(); j++) {
std::cout << connections[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
bool WeightedGraph::isPath(const int &node1, const int &node2) {
if ((node1 < 1) || (node2 > connections.size()) || (node2 < 1) || (node1 > connections.size())) {
throw "Node number is bigger than number of nodes or smaller than 1.";
}
std::vector<int> visited;
std::vector<int> path;
return searchPath(node1, node2, &visited);
}
bool WeightedGraph::searchPath(const int &node1, const int &node2, std::vector<int> *visitedNodes) {
if (std::find(visitedNodes->begin(), visitedNodes->end(), node1) == visitedNodes->end()) {
visitedNodes->emplace_back(node1);
if (connections[node1 - 1][node2 - 1]) {
return true;
}
for (int i = 0; i < connections[node1 - 1].size(); i++) {
if (connections[node1 - 1][i]) {
if (searchPath(i + 1, node2, visitedNodes)) {
return true;
} else {
return false;
}
}
}
return false;
}
return false;
}