using namespace std;
#include <vector>
#include <utility>
#include <iostream>
/*
Checks if the target int is in the v vector
Used in the getEdges and traverseAllNodes methods
*/
bool valueInVector(vector<int> v, int target) {
for (int i : v) {
if (i == target) {
return true;
}
}
return false;
}
class Graph {
private:
vector<pair<int, int>> graphVector{};
public:
void addEdge(int u, int v) {
pair<int, int> coordinates = pair<int, int> (u, v);
graphVector.push_back(coordinates);
}
/*
Prints each edge.
*/
void printEdges() {
for (pair<int, int> tempCoords : graphVector) {
int x = tempCoords.first;
int y = tempCoords.second;
cout << "(" << x << ", " << y << "), ";
}
}
/*
Returns the connected nodes of a specified node (argument). Use printVector method to print result
*/
vector<int> getEdges(int node) {
vector<int> connectedNodes;
for (pair<int, int> tempCoords : graphVector) {
if (tempCoords.first == node && !valueInVector(connectedNodes, tempCoords.second)) {
connectedNodes.push_back(tempCoords.second);
}
if (tempCoords.second == node && !valueInVector(connectedNodes, tempCoords.first)) {
connectedNodes.push_back(tempCoords.first);
}
}
return connectedNodes;
}
/*
There are other things that you can do when traversing, this method will simply
print out the node value if it hasn't been visited yet
*/
void traverseAllNodes() {
vector<int> visited;
for (pair<int, int> tempCoords : graphVector) {
int x = tempCoords.first;
if (!valueInVector(visited, x)) {
visited.push_back(x);
cout << x;
}
int y = tempCoords.second;
if (!valueInVector(visited, y)) {
visited.push_back(y);
cout << y;
}
}
}
Graph() {}
};
void printVector(vector<int> v) {
for (int i : v) {
cout << i << ", ";
}
}
int main(){
Graph g = Graph();
g.addEdge(1, 5);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(5, 6);
g.addEdge(1, 4);
cout << "Returning all edges of the graph: ";
g.printEdges();
cout << "\nGetting edges of the 1 node: ";
printVector(g.getEdges(1));
cout << "\nGetting edges of the 5 node: ";
printVector(g.getEdges(5));
cout << "\nTraversing all nodes: ";
g.traverseAllNodes();
}