# 实验报告图遍历的演示

``````#include <stdio.h>
#include <stdlib.h>
#define MAX 30
#define N 30
#define M 10
#define NULL 0
typedef struct ebox{
int ivex,jvex;
}ebox,*pebox;
typedef struct vexbox{
char *data;
pebox firstedge;
}vexbox,*pvexbox;
typedef struct amlgraph{
}amlgraph,pamlgraph;
typedef struct QNode{
int data;
struct QNode*next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));
Q.front->next=NULL;
return Q;
}
QueuePtr p;
int e;
p=Q->front->next;
e=p->data;
Q->front->next=p->next;
if(Q->rear==p)
Q->rear=Q->front;
free(p);
return e;
}
QueuePtr p;
p=(QueuePtr)malloc(sizeof(QNode));
p->data=e;
p->next=NULL;
Q->rear->next=p;
Q->rear=p;
}
if(Q.front==Q.rear)     return     1;
else return 0;
}
int visited[MAX]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
void initgraph(amlgraph &G,int n){
for(int i=0;i<n;i++)
}
void SCANF(char name[N][M],int n,amlgraph &G){
int i;
printf("请输入结点名称：\n");
for(i=0;i<n;i++){
scanf("%s",name[i]);
}
}
void CreateGraph(int n,amlgraph &G){
pebox p1,p2;
int i,j,k,m;
int mark;
initgraph(G,n);
printf("请输入边的数量:");
scanf("%d",&m);
for(k=0;k<m;k++){
printf("请输入第%d条边的两个顶点:",k+1);
scanf("%d%d",&i,&j);
p1=(pebox)malloc(sizeof(ebox));
p1->ivex=i;
p1->jvex=j;
else{
mark=0;
while(mark==0){
if(p2->ivex==i && p2->ilink==NULL) mark=1;
else if(p2->jvex==i && p2->jlink==NULL) mark=2;
}
}
else{
mark=0;
while(mark==0){
if(p2->ivex==j && p2->ilink==NULL) mark=1;
else if(p2->jvex==j && p2->jlink==NULL) mark=2;
}
}
}
}
void visit(amlgraph G,int v){
visited[v]=1;
}
void DFS(amlgraph G,int v){
pebox p;
int mark;
if(visited[v]==0) visit(G,v);
else return;
if(p==NULL) return;
else{
mark=0;
while(mark==0){
if(p->ivex==v){
if(visited[p->jvex]==0){
printf("\t\t\t<%d,%d>",p->ivex,p->jvex);
DFS(G,p->jvex);
}
}
else{
if(visited[p->ivex]==0){
printf("\t\t\t<%d,%d>",p->jvex,p->ivex);
DFS(G,p->ivex);
}
}
}
}
}
void BFS(amlgraph G,int v){
pebox p;
int e;
int mark;
Q=InitQueue();
if(visited[v]==0) visit(G,v);
else return;
EnQueue(&Q,v);
while(QueueEmpty(Q)!=1){
e=DeQueue(&Q);
if(p==NULL) return;
mark=0;
while(mark==0){
if(p->ivex==e){
if(visited[p->jvex]==0){
EnQueue(&Q,p->jvex);
printf("\t\t\t<%d,%d>",p->ivex,p->jvex);
visit(G,p->jvex);
}
}
else{
if(visited[p->ivex]==0){
EnQueue(&Q,p->ivex);
printf("\t\t\t<%d,%d>",p->jvex,p->ivex);
visit(G,p->ivex);
}
}
}
}
}
void clear(int v[MAX]){
int i;
for(i=0;i<MAX;i++)
v[i]=0;
}
int main()
{
int n,v,i;
char name[N][M];
amlgraph G;
printf("请输入结点的数量:");
scanf("%d",&n);
SCANF(name,n,G);
CreateGraph(n,G);
printf("请输入从哪一个结点开始访问:");
scanf("%d",&v);
printf("该图的深度优先遍历和所经过的边为:");

DFS(G,v);

clear(visited);
printf("\n该图的广度优先遍历和所经过的边为:");
int j=0;

BFS(G,v);

printf("\n两种遍历结束!\n");
}
``````

原文作者：数据结构之图
原文地址: https://blog.csdn.net/a197p/article/details/46475229
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。