//深度和宽度遍历图,邻接表存储
#include<iostream>
#include<queue>
#include<stdlib.h>
#include<string.h>
#define maxn 10010
using namespace std;
int visited[maxn];
typedef struct Enode {
int adjVex; //任意与u相邻的点
int w; //边权
struct Enode *nextArc; //指向下一个边结点
}Enode;
typedef struct {
int n, e;
Enode **a;
}Lgraph;
//单一顶点深搜
void dfs(int v, int visited[], Lgraph g) {
Enode *w;
cout << v << " "; //访问结点v
visited[v] = 1;
for (w = g.a[v]; w; w = w->nextArc) //访问邻接点
{
if (!visited[w->adjVex]) {
dfs(w->adjVex, visited, g);
}
}
}
//初始化
int init(Lgraph *lg, int nSize) {
lg->n = nSize;
lg->e = 0;
lg->a = (Enode **)malloc(nSize * sizeof(Enode *));
if (!lg->a) return 0;
for (int i = 0; i < lg->n; i++) {
lg->a[i] = NULL;
}
return 1;
}
//插入边
int Insert(Lgraph *lg, int u, int v, int w) {
if (u<0 || v<0 || u>lg->n - 1 || v>lg->n - 1 || u == v) return 0;
Enode *p;
p = (Enode *)malloc(sizeof(Enode));
p->adjVex = v;
p->w = w;
p->nextArc = lg->a[u];
lg->a[u] = p;
lg->e++;
return 1;
}
//全图深搜
void dfsGraph(Lgraph g) {
int i;
int *visited = (int *)malloc(g.n * sizeof(int));
for (int i = 0; i < g.n; i++)
visited[i] = 0;
for (int i = 0; i < g.n; i++) {
if (!visited[i]) {
dfs(i, visited, g);
}
}
free(visited);
}
int main() {
Lgraph lg;
int n, u, v, w, visited[maxn], p;
memset(visited, 0, sizeof(visited));
cout << "请输入顶点的个数." << endl;
cin >> n;
init(&lg, n);
cout << "请输入带插入边的两个端点和边权.(以0 0 0结尾)" << endl;
while (cin >> u >> v >> w) {
if (u == 0 && v == 0 && w == 0) break;
Insert(&lg, u, v, w);
}
cout << "请输入搜索的起点." << endl;
cin >> u;
//单一顶点深搜
cout << "单一顶点深搜:";
dfs(u, visited, lg);
cout << endl;
//全图深搜
cout << "全图深搜:";
dfsGraph(lg);
cout << endl;
cout << "深搜结束" << endl;
system("pause");
return 0;
}
大二(上) 数据结构 深度和宽度遍历图,邻接表存储
猜你喜欢
转载自blog.csdn.net/qq_43271844/article/details/86551385
今日推荐
周排行