数据结构NOJ——20基于图的广度优先搜索策略

在这里插入图片描述

#include<iostream>
#include<queue>//使用了STL
using namespace std;

typedef int VertexType;
#define NUM 100

//表头结点
typedef struct HNode {
	VertexType data;
	struct ArcNode* firstarc;
}HNode,AdjList[NUM];

//边结点
typedef struct ArcNode {
	int AdjVex;
	struct ArcNode* next;
}ArcNode;

//定义图
typedef struct {
	AdjList vertices;
	int vexnum, arcnum;
}Graph,*DGraph;

int Locate(DGraph G, int v) {
	for (int i = 0; i < G->vexnum; i++) {
		if (G->vertices[i].data == v)
			return i;
	}
}

void CreatGraph(DGraph& G) {
	cin >> G->vexnum >> G->arcnum;
	for (int i = 0; i < G->vexnum; i++)
		cin >> G->vertices[i].data;
	int v1, v2,x, y;
	for (int j = 0; j < G->arcnum; j++) {
		cin >> v1 >> v2;
		x = Locate(G, v1);
		y = Locate(G, v2);
		ArcNode* p = new ArcNode;
		p->AdjVex = y;
		p->next = G->vertices[x].firstarc;
		G->vertices[x].firstarc = p;
	}
}

void BFS(DGraph G, int v1, int v2) {
	int vi = Locate(G, v1);
	int vj = Locate(G, v2);

	int visited[10];
	visited[vi] = 1;

	ArcNode* p;

	queue<VertexType>q;
	q.push(vi);
	while (!q.empty()) {
		int v=q.front();//返回栈顶元素但不弹出
		q.pop();
		for (p = G->vertices[v].firstarc; p != NULL; p = p->next) {
			int w = p->AdjVex;
			if (w == vj) cout << "yes"; break;
			if (!visited[w]) {
				visited[w] = 1;
				q.push(w);
			}
		}
	}
}

void main() {
	DGraph G = new Graph;
	CreatGraph(G);
	int vi, vj;
	cin >> vi >> vj;
	BFS(G, vi , vj);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值