图的表示
有两种方法:邻接表和邻接矩阵,下面分别是无向图和有向图的两种表示方法,均来自算法导论
图的遍历
分为广度优先遍历和深度优先遍历下面分别就两种方法给出伪代码和c++代码,其中图的存储使用邻接矩阵存储。
- 广度优先遍历
伪代码
C++代码
#include <iostream>
#include <queue>
using namespace std;
#define N 6
queue<int> Queue;
struct adj_matrix {
int vertex[N];
int edge[N][N];
};
struct adj_matrix matrix = {
{ 1, 2, 3, 4, 5, 6 },
{ { 0, 1, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 1, 0 },
{ 0, 0, 0, 0, 1, 1 },
{ 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 1 } }
};
int visit[N];
void bfs_visit(struct adj_matrix *G, int s)
{
cout << G->vertex[s] << " ";
visit[s] = 1;
Queue.push(s);
int u;
while (!Queue.empty()){
u = Queue.front();
Queue.pop();
for (int v = 0; v < N; v++){
if (G->edge[u][v] == 1 && visit[v] == 0){
cout << G->vertex[v] << " ";
visit[v] = 1;
Queue.push(v);
}
}
}
}
void bfs(struct adj_matrix *G){
for (int u = 0; u < N; u++){
if (visit[u] == 0)
bfs_visit(G, u);
}
}
int main(void)
{
memset(visit, 0, N);
bfs(&matrix);
cout << endl;
getchar();
return 0;
}
- 深度优先遍历
伪代码
C++代码
#include <iostream>
using namespace std;
#define N 6
struct adj_matrix {
int vertex[N];
int edge[N][N];
};
struct adj_matrix matrix = {
{ 1, 2, 3, 4, 5, 6 },
{ { 0, 1, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 1, 0 },
{ 0, 0, 0, 0, 1, 1 },
{ 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 1 } }
};
int visit[N] = { 0, 0, 0, 0, 0, 0 };
void dfs_visit(struct adj_matrix *G, int u)
{
int v;
visit[u] = 1;
cout << G->vertex[u] << " ";
for (v = 0; v < N; v++) {
if (G->edge[u][v] == 1 && visit[v] != 1) {
dfs_visit(G, v);
}
}
}
void dfs(struct adj_matrix *G)
{
int u;
for (u = 0; u < N; u++) {
if (visit[u] != 1) {
dfs_visit(G, u);
}
}
}
int main(void)
{
dfs(&matrix);
cout << endl;
getchar();
return 0;
}