使用STL的vector容器模拟邻接表
本代码中 队列均使用STL内置队列,如有需要请自行修改。
// 运行环境:cpp11
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
// 最大节点数量
const int MAXN = 2000;
int vis[2000]; // 标记节点是否被访问过的
struct edge {
int to, cost; // cost 为权重 to 为当前边的终点
edge(int t, int c) {
to = t;
cost = c;
}
};
vector<edge> G[MAXN];
void add_edge(int from, int to, int cost)
{
G[from].push_back(edge{to, cost});
G[to].push_back(edge{from, cost}); // 如果是有向图就注释这句
}
// 深度优先遍历图
void dfs(int s)
{
vis[s] = 1;
cout << s << " ";
for (int i=0; i<G[s].size(); i++)
{
if (!vis[G[s][i].to])
{
dfs(G[s][i].to);
}
}
}
// 广度优先遍历
void bfs(int s)
{
queue<int> q;
q.push(s);
vis[s] = 1;
cout << s << " ";
while (!q.empty())
{
int temp = q.front();
q.pop();
for (int i=0; i<G[temp].size(); i++)
{
if (!vis[G[temp][i].to])
{
q.push(G[temp][i].to);
cout << G[temp][i].to << " ";
vis[G[temp][i].to] = 1;
}
}
}
cout << endl;
}
int main()
{
// n为边的数量
int n;
cin >> n;
for (int i=0; i<n; i++)
{
int from, to, cost;
cin >> from >> to >> cost;
add_edge(from, to, cost);
}
dfs(0);
cout << endl;
memset(vis, 0, sizeof(vis));
bfs(0);
return 0;
}
使用链表的邻接表存储加深搜广搜
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 2000;
int vis[2000];
// 边结构体,成员为指向的节点,下一条边地址,权重信息等
struct ArcNode
{
int adjvex; // 该边所指向的节点
ArcNode *nextarc; // 指向下一条边地址
int cost; // 边权重,本代码没使用
ArcNode() {
nextarc = NULL;
cost = 0;
}
};
// 节点结构体,成员为节点信息,第一条边地址
struct vNode
{
char data; // 节点信息,基本不用
ArcNode *fristarc; // 指向第一条边的信息
vNode() {
fristarc = NULL;
}
};
// 图结构体,成员为节点集合,边数,节点数
struct graph
{
vNode adjlist[MAXN];
int n, e;
};
// 深搜
void dfs(graph *G, int s)
{
ArcNode *p;
vis[s] = 1;
cout << s << " ";
p = G->adjlist[s].fristarc;
while (p)
{
if (!vis[p->adjvex])
{
dfs(G, p->adjvex);
}
p = p->nextarc;
}
}
// 广搜
void bfs(graph *G, int s)
{
queue<int> q;
q.push(s);
vis[s] = 1;
cout << s << " ";
while (!q.empty())
{
ArcNode *p = G->adjlist[q.front()].fristarc;
q.pop();
while (p)
{
if (!vis[p->adjvex])
{
vis[p->adjvex] = 1;
q.push(p->adjvex);
cout << p->adjvex << " ";
}
p = p->nextarc;
}
}
cout << endl;
}
int main()
{
int n, e;
graph *G = new graph;
cin >> n >> e;
G->n = n;
G->e = e;
for (int i=0; i<n; i++)
{
int from, to;
ArcNode *s = new ArcNode;
cin >> from >> to;
s->adjvex = to;
// 采用头插法,更加方便,不需要遍历到链表尾
s->nextarc = G->adjlist[from].fristarc;
G->adjlist[from].fristarc = s;
}
dfs(G, 0);
cout << endl;
memset(vis, 0, sizeof(vis));
bfs(G, 0);
return 0;
}