#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);
}
数据结构NOJ——20基于图的广度优先搜索策略
最新推荐文章于 2024-09-13 18:30:00 发布