任务描述
一个连通图采用邻接表作为存储结构。设计一个算法,实现从顶点v出发的深度优先遍历的非递归过程。
编程要求
输入
多组数据,每组m+2数据行。第一行有两个数字n和m,代表有n个顶点和m条边。顶点编号为1到n。第二行到第m+1行每行有两个整数h和k,代表边依附的两个顶点。第m+2行有一个整数d,代表从d开始遍历。当n和m都等于0时,输入结束。
输出
每组数据输出一行,为深度优先搜索的遍历结果。每两个数字之间用空格隔开。
测试说明
平台会对你编写的代码进行测试:
测试输入:
3 2
1 2
1 3
1
2 1
1 2
2
0 0
预期输出:
1 2 3
2 1
C代码
自曾氏同学
栈的四个初始化似乎并不必要
h文件
#include<iostream>
#include<stack>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
using namespace std;
typedef struct VNode{
int data;
struct VNode *next;
}VNode,*NodeList;
typedef struct{
NodeList V[MAXSIZE];
int vexnum,arcnum;
}ALGraph;
typedef struct
{
//顺序栈
int *base; //栈底指针
int *top; //栈顶指针
int stacksize; //栈可用的最大容量
}SqStack;
int CreateUDG(ALGraph &G,int vexnum,int arcnum)
{
//采用邻接表表示法,创建无向图G
G.vexnum = vexnum;
G.arcnum = arcnum;
for(int i=1;i<=vexnum; i ++){
G.V[i] = new VNode;
G.V[i]->next = NULL;
G.V[i]->data = i;
}
while(arcnum--){
int v1,v2;
cin>>v1>>v2;
NodeList p1 =new VNode;
p1->data =v2;
p1->next =G.V[v1]->next;
G.V[v1]->next = p1;
NodeList p2 =new VNode;
p2->data = v1;
p2->next = G.V[v2]->next;
G.V[v2]->next = p2;
}
return OK;
}
void DFS(ALGraph G,int v,SqStack S)
{
//从第v个顶点出发非递归实现深度优先遍历图G
cout<<v;
int top=0,visited[MAXSIZE],Stack[MAXSIZE];
for(int i=0;i<MAXSIZE;i++)
visited[i]=0;
Stack[top++]=v;
visited[v]=1;
while(top>0)
{
int flag = 0;
NodeList p=G.V[Stack[top-1]];
while(p)
{
if(!visited[p->data])
flag=p->data;
p=p->next;
}
if(flag == 0)
top--;
else
{
cout<<" "<<flag;
Stack[top++]=flag;
visited[flag]=1;
}
}
cout<<endl;
return;
}
主函数文件不可编辑
#include<iostream>
#include "282.h"
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m)
{
if(n==0&&m==0) break;
ALGraph G;
SqStack S;
CreateUDG(G,n,m); //创建无向图G
int d; //从d开始遍历
cin>>d;
DFS(G,d,S); //基于邻接表的深度优先遍历
}
return 0;
}