-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathundirectGraph.h
144 lines (124 loc) · 2.95 KB
/
undirectGraph.h
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <unordered_map>
#include <unordered_set>
#include <climits>
#include <queue>
#include <vector>
template <>
struct std::hash<std::pair<int, int>>
{
size_t operator()(std::pair<int, int> p) const noexcept
{
return ((size_t)p.first << 32) | p.second;
}
};
using std::max;
using std::min;
using std::swap;
class undirectGraph
{
public:
using NumType = int;
private:
std::unordered_map<NumType, std::unordered_set<NumType>> graph_;
public:
undirectGraph(/* args */);
~undirectGraph();
void connect(int src, int dest);
std::unordered_map<NumType, NumType> distance(int dest);
};
undirectGraph::undirectGraph(/* args */)
{
}
undirectGraph::~undirectGraph()
{
}
void undirectGraph::connect(int src, int dest)
{
graph_[src].insert(dest);
graph_[dest].insert(src);
}
std::unordered_map<undirectGraph::NumType, undirectGraph::NumType> undirectGraph::distance(int dest)
{
std::unordered_map<NumType, NumType> result;
std::queue<NumType> next;
std::queue<NumType> nextBuffer;
std::unordered_set<NumType> checked;
next.push(dest);
NumType depth = 0;
while (!next.empty() || !nextBuffer.empty())
{
while (!next.empty())
{
if (!checked.count(next.front()))
{
checked.insert(next.front());
result[next.front()] = depth;
for (auto near : graph_[next.front()])
{
if (!checked.count(near))
{
nextBuffer.push(near);
}
}
}
next.pop();
}
swap(nextBuffer, next);
depth++;
}
return result;
}
class undirectGraph
{
public:
using NumType = int;
private:
std::vector<std::vector<NumType>> graph_;
int size_;
public:
undirectGraph(int s);
~undirectGraph();
void connect(int src, int dest);
std::vector<NumType> distance(int dest);
};
undirectGraph::undirectGraph(int s) : graph_(s), size_{s}
{
}
undirectGraph::~undirectGraph()
{
}
void undirectGraph::connect(int src, int dest)
{
graph_[src].push_back(dest);
graph_[dest].push_back(src);
}
std::vector<undirectGraph::NumType> undirectGraph::distance(int dest)
{
std::vector<NumType> result(size_,0);
std::queue<NumType> next;
std::queue<NumType> nextBuffer;
std::vector<char> checked(size_,0);
next.push(dest);
checked[0] =1;
NumType depth = 0;
while (!next.empty() || !nextBuffer.empty())
{
while (!next.empty())
{
auto niStart = next.front();
result[niStart] = depth;
for (auto near : graph_[niStart])
{
if (!checked[near])
{
checked[near] =1;
nextBuffer.push(near);
}
}
next.pop();
}
swap(nextBuffer, next);
depth++;
}
return result;
}