Skip to content

Commit 3a0ab5e

Browse files
committed
feat: add graph data structure
1 parent 33f5897 commit 3a0ab5e

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

basic_data_structure/graph/graph.cpp

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2021-03-07 22:08:23
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2021-03-07 23:00:37
6+
*/
7+
8+
/**
9+
* 图是一种非线性数据结构,由【节点(定点) vertex】和【边 edge】组成,每条边连接一对定点。根据边的方向有无,
10+
* 图可以分为【有向图】和【无向图】。
11+
* 如 ./graph.png 所示,该无向图的 顶点 和 边 集合分别为:
12+
* 1. 顶点集合:vertices = {1, 2, 3, 4, 5}
13+
* 2. 边集合:edges = {{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 4}, {3, 5}, {4, 5}}
14+
*
15+
* 表示图的方法有两种:
16+
* 1. 邻接矩阵:使用数组 vertices 存储顶点,邻接矩阵 edges 存储边;edges[i][j] 代表节点 i+1 和 节点 j+1之间是否有边。
17+
* vertices=[1,2,3,4,5]
18+
*
19+
* ⎡0 1 1 1 1⎤
20+
* ⎢1 0 0 1 0⎥
21+
* edges = ⎢1 0 0 0 1⎥
22+
* ⎢1 1 0 0 1⎥
23+
* ⎣1 0 1 1 0⎦
24+
*
25+
*/
26+
27+
// 代码表示上述数据结构​
28+
int vetices[5] = {1, 2, 3, 4, 5};
29+
int edges[5][5] = {{0, 1, 1, 1, 1},
30+
{1, 0, 0, 1, 0},
31+
{1, 0, 0, 0, 1},
32+
{1, 1, 0, 0, 1},
33+
{1, 0, 1, 1, 0}};
34+
35+
/**
36+
* 2. 邻接表:使用数组 vetices 存储顶点,邻接表 edges 存储边。edges 为一个二维容器,第一维 i 代表顶点索引,
37+
* 第二维 edges[i] 存储次顶点对应的边集合;例如 edges[0] = [1, 2, 3, 4] 代表 vertices[0] 的边集合为[1, 2, 3, 4]。
38+
* vertices=[1,2,3,4,5]
39+
*
40+
* ⎡[1 2 3 4]⎤
41+
* ⎢[0 3] ⎥
42+
* edges = ⎢[0 4] ⎥
43+
* ⎢[0 1 4] ⎥
44+
* ⎣[0 2 3] ⎦
45+
*/
46+
47+
int vertices1[5] = {1, 2, 3, 4, 5};
48+
vector<vector<int>> edges1;
49+
50+
vector<int> edge_1 = {1, 2, 3, 4};
51+
vector<int> edge_2 = {0, 3};
52+
vector<int> edge_3 = {0, 4};
53+
vector<int> edge_4 = {0, 1, 4};
54+
vector<int> edge_5 = {0, 2, 3};
55+
edges1.push_back(edge_1);
56+
edges1.push_back(edge_2);
57+
edges1.push_back(edge_3);
58+
edges1.push_back(edge_4);
59+
edges1.push_back(edge_5);
60+
61+
/**
62+
* 邻接矩阵 VS 邻接表 :
63+
* 邻接矩阵的大小只与节点数量有关,即 N^2,其中 N 为节点数量。因此,当边数量明显少于节点数量时,使用邻接矩阵存储图会造成较大的内存浪费。
64+
* 因此,邻接矩阵 适合存储稠密图(顶点较少、边较多),邻接表 适合存储稀疏图(顶点较多、边较少)。
65+
*/

basic_data_structure/graph/graph.png

89.2 KB
Loading

0 commit comments

Comments
 (0)