深度优先搜索

好吧。。这是最基础的代码,刚学会的。=w=


#include <iostream>
using namespace std;
#define MAX_VERTEX_NUM 20

struct ArcNode{
	int adjvex;
	ArcNode *nectarc;
};

struct VexNode{
	int data;
	ArcNode *firstarc;
};

struct Graph{
	VexNode vertices[MAX_VERTEX_NUM];
	int vexnum,arcnum;
};

bool ListInsert(VexNode *L,int i,ArcNode e){
	int j=0;
	ArcNode *s,*t;
	s=new ArcNode();
	s->adjvex=e.adjvex;
	VexNode *p=L;
	if (!p||j>i-1)
		return false;
	if (i==1){
		s->nectarc=p->firstarc;
		p->firstarc=s;
	}
	else {
		t=p->firstarc;
		while (j<i-1){
			t=t->nectarc;
		}
		s->nectarc=t->nectarc;
		t->nectarc=s;
	}
	return true;
}

void CreateGraph(Graph *G){
	int i,j,k;
	int va,vb;
	ArcNode e;
	cout<<"输入图的顶点数、边数:";
	cin>>(*G).vexnum>>(*G).arcnum;
	for (i=0;i<(*G).vexnum;i++){
		(*G).vertices[i].data=i;
		(*G).vertices[i].firstarc=NULL;
	}
	cout<<"输入弧头弧尾:"<<endl;
	for (k=0;k<(*G).arcnum;k++){
		cin>>va>>vb;
		e.adjvex=va;
		ListInsert(&(*G).vertices[vb],1,e);
		e.adjvex=vb;
		ListInsert(&(*G).vertices[va],1,e);
	}
}

bool visited[MAX_VERTEX_NUM];

void VisitFunc(int v){
	cout<<v<<' ';
}

void DFS(Graph G,int v){
	int w;
	ArcNode *p;
	visited[v]=true;
	VisitFunc(G.vertices[v].data);
	p=G.vertices[v].firstarc;
	while (p){
		w=p->adjvex;
		if (!visited[w])
			DFS(G,w);
		p=p->nectarc;
	}
}

void DFSTraverse(Graph G){
	int v;
	for (v=0;v<G.vexnum;v++)
		visited[v]=false;
	for (v=0;v<G.vexnum;v++)
		if (!visited[v])
			DFS(G,v);
}

int main(){
	Graph G;
	CreateGraph(&G);
	DFSTraverse(G);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值