图的深度搜索和广度搜索代码c

#include<iostream>
#include<queue> 
using namespace std;
typedef int VertexType;
#define MaxVertexNum 100
typedef int EdgeType;
typedef struct{
	VertexType Vex[MaxVertexNum];
	EdgeType Edge[MaxVertexNum][MaxVertexNum];
	int vexnum,arcnum;
	bool visited[MaxVertexNum][MaxVertexNum];
}MGraph;
bool Adjacent(MGraph G,VertexType x,VertexType y){ //判断边<x,y>或者<y,x>是否存在 
		if(G.Edge[x-1][y-1]==1)
			return true;
		else return false;
}
int Neighbors(MGraph G,VertexType x){ //输出G的临接结点 
	for(int i=0;i<G.vexnum;i++){
		if(G.Edge[x-1][i]==1){
			cout<<i+1<<" ";
		}
	}
	return 0;
}
int InsertVertex(MGraph &G,int x){
	return 0;
}
int FirstNeighbor(MGraph &G,int x){ //图G中的顶点x的第一个邻接点,若有则返回顶点号,没有返回-1 
	for(int i=0;i<G.vexnum;i++){
		if(G.Edge[x][i]==1&&G.visited[x][i]==false){
			G.visited[x][i]=true;
			return i;
		}
	}
	return -1; 
}
int NextNeighbor(MGraph &G,int x,int y){
	for(int i=0;i<G.vexnum;i++){
		if(G.Edge[x][i]==1&&G.visited[x][i]==false&&i!=(y)){
			G.visited[x][i]=true;
			return i;
		}
	}
	return -1;
}
bool visited[MaxVertexNum];
void DFS(MGraph G,int v){
	cout<<v<<" ";
	visited[v]=true;
	int w;
	for(w=FirstNeighbor(G,v);w>=0;w=NextNeighbor(G,v,w)){
		if(!visited[w]){
			DFS(G,w);
		}
	}
}
bool DFSTraverse(MGraph G){
	for(int v=0;v<G.vexnum;v++){
		visited[v]=false;
	}
	for(int v=0;v<G.vexnum;v++){
		if(!visited[v]){
			DFS(G,v);
		}
	}
}
void BFS(MGraph G,VertexType v){
	int w;
	cout<<v<<" ";
	queue<VertexType> Q;
	visited[v]=true;
	Q.push(v);
	while(Q.size()){
		int x=Q.front();
		Q.pop();
		for(w=FirstNeighbor(G,x);w>=0;w=NextNeighbor(G,x,w)){
			if(!visited[w]){
				cout<<w<<" ";
				visited[w]=true;
				Q.push(w);
			}
		}
	}
	                    
} 
void BFSTraverse(MGraph G){
	for(int i=0;i<G.vexnum;i++){
		visited[i]=false;
	}
	for(int i=0;i<G.vexnum;i++){
		if(!visited[i])
		BFS(G,i);
	}
}
int main(){
	MGraph G;
	int vexnum,arcnum;
	cin>>vexnum;
	for(int i=1;i<=vexnum;i++){
		G.Vex[i]=i;
	}
	G.vexnum=vexnum;
	for(int i=0;i<vexnum;i++){
		for(int j=0;j<vexnum;j++){
			int n;
			cin>>n;
			G.Edge[i][j]=n;
			G.visited[i][j]=false;
			if(n==1){
				G.arcnum++;
			}
		}
	}
//	cout<<int(Adjacent(G,2,3));
//	Neighbors(G,2);
//	BFSTraverse(G);
	BFS(G,2);
//	DFS(G,3);
	return 0;
}
//5
//0 1 0 1 0
//1 0 1 0 1
//0 1 0 1 1
//1 0 1 0 0
//0 1 1 0 0

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值