图相关
###1. 图的表示
- 邻接矩阵:这种表示方式存储了每一个顶点,因此大小为$o(n^2)$,对于那些稀疏矩阵来说很浪费空间。
- 邻接表:存储每一个顶点和其他顶点的关系时将其顶点按升序排列,可以快速定位至某一顶点。
1 |
|
###2. 图的遍历
深度优先遍历(DFS)
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
26std::vector<int> graph::dfs(int beg) const
{
std::vector<int> pre(current_size, -1);
std::vector<int> state(current_size, -1); //-1代表未被访问,0代表正在访问,1代表访问完成
dfs(beg, pre, state);
for (int i = 0; i < current_size; ++i)
{
if(state[i] == -1)
dfs(i, pre, state);
}
return pre;
}
void graph::dfs(int beg, std::vector<int> &pre, std::vector<int>& state) const
{
state[beg] = 0;
for (auto _beg = cbegin(beg);_beg != cend(beg);++_beg)
{
int i = _beg->first;
if (state[i] == -1)
{
pre[i] = beg;
dfs(i, pre, state);
}
}
state[beg] = 1;
}广度优先遍历(BFS)
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
34std::vector<int> graph::bfs(int beg) const
{
std::vector<int> pre(current_size, -1);
std::vector<int> state(current_size, -1); //-1代表未被访问,0代表正在访问,1代表访问完成
bfs(beg, pre, state);
for (int i = 0; i < current_size; ++i)
{
if(state[i] == -1)
bfs(i, pre, state);
}
return pre;
}
void graph::bfs(int beg, std::vector<int> &pre, std::vector<int> &state) const
{
std::queue<int> q;
q.push(beg);
while(!q.empty())
{
int u = q.front();
state[u] = 0;
for (auto _beg = cbegin(u);_beg != cend(u);++_beg)
{
int i = _beg->first;
if (state[i] == -1)
{
pre[i] = u;
q.push(i);
}
}
q.pop();
state[u] = 1;
}
}