-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.hpp
More file actions
72 lines (58 loc) · 1.89 KB
/
Graph.hpp
File metadata and controls
72 lines (58 loc) · 1.89 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
#pragma once
#include <vector>
#include <set> // To store neighbors, allows easy alphabetical sorting later
#include <queue> // For BFS
#include <map> // For BFS visited/distance tracking
#include <limits> // For std::numeric_limits
//Vertices represent users, edges represent friendships.
class Graph {
private:
// Adjacency list: user_id -> set_of_friend_ids
std::vector<std::set<int>> adjList;
int numVertices;
public:
Graph() : numVertices(0) {}
int addVertex() {
adjList.push_back(std::set<int>());
return numVertices++; //return userID
}
void addEdge(int u, int v) {
if (u < numVertices && v < numVertices) {
adjList[u].insert(v);
adjList[v].insert(u);
}
}
const std::set<int>& getNeighbors(int u) const { //Friends of a user
if (u < numVertices) {
return adjList[u];
}
static const std::set<int> emptySet;
return emptySet; //For Invalid USER ID
}
int getNumVertices() const {
return numVertices;
}
int getDegreesOfSeparation(int startNode, int endNode) { //uses BFS
if (startNode == endNode) return 0;
std::queue<std::pair<int, int>> q; //{node, distance}
std::map<int, int> distance; //For tracking visited nodes and distance
q.push({startNode, 0});
distance[startNode] = 0;
while (!q.empty()) {
std::pair<int, int> current = q.front();
q.pop();
int u = current.first;
int dist = current.second;
for (int v : adjList[u]) {
if (distance.find(v) == distance.end()) {
if (v == endNode) {
return dist + 1;
}
distance[v] = dist + 1;
q.push({v, dist + 1});
}
}
}
return -1;
}
};