#include "cstdio"
#include "cstdlib"
#define max_size 256
typedef struct _EdgeNode {
int adjvex;
struct _EdgeNode *next;
} EdgeNode;
typedef struct _VertexNode {
char data;
EdgeNode *first;
} VertexNode, AdjList;
typedef struct _AdjListGraph {
AdjList *adjList;
int vex;
int edge;
} AdjListGraph;
bool visited[max_size];
void InitGraph(AdjListGraph *G) {
G->adjList = new AdjList[max_size];
G->edge = 0;
G->vex = 0;
for (int i = 0; i < max_size; i++) {
visited[i] = false;
}
}
int Location(AdjListGraph *G, char c) {
for (int i = 0; i < G->vex; i++) {
if (G->adjList[i].data == c) {
return i;
}
}
return -1;
}
void CreateGraph(AdjListGraph *G) {
printf("请输入相关边的顶点数和边数:\n");
scanf("%d %d", &G->vex, &G->edge);
printf("请输入相关顶点:\n");
for (int i = 0; i < G->vex; i++) {
getchar();
scanf("%c", &G->adjList[i].data);
G->adjList[i].first = NULL;
}
char v1, v2;
int i1, i2;
printf("输入相关联的边:\n");
for (int i = 0; i < G->edge; i++) {
getchar();
scanf("%c %c", &v1, &v2);
i1 = Location(G, v1);
i2 = Location(G, v2);
if (i1 != -1 && i2 != -2) {
EdgeNode *temp = new EdgeNode;
temp->adjvex = i2;
temp->next = G->adjList[i1].first;
G->adjList[i1].first = temp;
}
}
}
void DFS(AdjListGraph *G, int v) {
int next = -1;
if (visited[v]) return;
printf("%c", G->adjList[v].data);
visited[v] = true;
EdgeNode *temp = G->adjList[v].first;
while (temp) {
next = temp->adjvex;
temp = temp->next;
if (visited[next] == false) {
DFS(G, next);
}
}
}
void DFS_Main(AdjListGraph *G) {
for (int i = 0; i < G->vex; i++) {
if (visited[i] == false) {
DFS(G, i);
}
}
printf("\n");
}
void Display(AdjListGraph *G) {
for (int i = 0; i < G->vex; i++) {
printf("顶点: %c", G->adjList[i].data);
EdgeNode *temp = G->adjList[i].first;
while (temp) {
printf("-> %c ", G->adjList[temp->adjvex].data);
temp = temp->next;
}
}
printf("\n");
}
int main() {
AdjListGraph G;
InitGraph(&G);
CreateGraph(&G);
DFS_Main(&G);
Display(&G);
return 0;
}
/*对图上的顶点进行广度遍历*/
void BFS(AdjListGraph &G, int v) {
queue<int> q;
int cur;
int next;
q.push(v);
while (!q.empty()) { //队列非空
cur = q.front(); //取队头元素
if (visited[cur] == false) { //当前顶点还没有被访问
cout << G.adjlist[cur].data << " ";
visited[cur] = true; //设置为已访问
}
q.pop(); //出队列
EdgeNode *tp = G.adjlist[cur].first;
while (tp != NULL) {
next = tp->adjvex;
tp = tp->next;
q.push(next); //将第一个邻接点入队
}
}
}
/*对所有顶点进行广度遍历*/
void BFS_Main(AdjListGraph &G) {
for (int i = 0; i < G.vex; i++) {
if (visited[i] == false) {
BFS(G, i);
}
}
}