一.图的邻接矩阵表示法
struct graph
{
vector<vector<int>> cost;//邻接矩阵
vector<string> vertex;//顶点的值,用string较好,节点的名字可以是v1,v2等等
};
二.图的遍历
2.0 图的遍历测试所用到的图:
邻接矩阵表示:
//测试用的图
vector<vector<int>> test_graph(7, vector<int>(7, 0));
test_graph[0][1] = 20;
test_graph[0][2] = 50;
test_graph[0][3] = 30;
test_graph[1][2] = 25;
test_graph[1][5] = 70;
test_graph[2][3] = 40;
test_graph[2][4] = 25;
test_graph[2][5] = 50;
test_graph[3][4] = 55;
test_graph[4][5] = 10;
test_graph[4][6] = 70;
test_graph[5][6] = 50;
2.1 BFS(广度优先遍历)
代码:
void BFS(graph g,int beg){//begin为开始遍历顶点的标号
int N = g.cost.size();
vector<bool> visited(N, false);
queue<int> q;//用于存放节点的标号
if (!visited[beg]) {
cout << g.vertex[beg] << " ";
visited[beg] = true;//标记为已访问
q.push(beg);
}
while (!q.empty()) {
int cur = q.front();
q.pop();//弹出
for (int i = 0;i < N;++i) {
if ((g.cost[cur][i] != 0) && !visited[i]) {//若有边且未访问过,则访问之
cout << g.vertex[i] << " ";
visited[i] = true;//标记为已访问
q.push(i);
}
}
}
}
测试部分:
//BFS
graph g;
g.cost = test_graph;
g.vertex = { "v1","v2","v3","v4","v5","v6","v7" };
BFS(g, 0);
BFS输出结果:
2.2 DFS(深度优先搜索)
代码:
vector<bool> visited(100, false);
void DFS(graph g, int beg) {
//访问该点
cout << g.vertex[beg] << " ";
visited[beg] = true;
for (int i = 0;i < g.cost.size();++i) {//有边且未访问过时
if ((g.cost[beg][i] != 0) && !visited[i])
DFS(g, i);
}
}
DFS测试部分:
//DFS
graph g;
g.cost = test_graph;
g.vertex = { "v1","v2","v3","v4","v5","v6","v7" };
DFS(g, 0);
DFS测试结果: