图 (Graph) 主要由两个要素组成:顶点 (或节点)(Vertex) 和边 (Edge)。
图主要分为无向图(Undirected Graph),有向图(Directed Graph),和加权图(Weighted Graph)。

例如这是一个无向图↑
图的储存
图的储存可以通过结构体和vector数组实现,通过输入图的边来储存。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <iostream> #include <vector> using namespace std; int n,m; vector<int> G[100005]; int main(int argc, char *argv[]) { cin >> n >> m; for(int i = 1;i <= m;i++) { int u,v; cin >> u >> v; G[u].push_back(v); G[v].push_back(u); } }
|
图的遍历
图的遍历可以使用深度优先搜索(DFS)和广度优先搜索(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
| bool vis[100005]; void dfs(int x) { vis[x] = 1; for(auto p : G[x]) { if(vis[p]) continue; dfs(p); } } void bfs(int x) { vis[x] = 1; q.push(x); while(!q.empty()) { int u = q.front(); q.pop(); for(auto p : G[u]) { if(vis[p]) continue; vis[p] = 1; q.push(p); } } }
|