题目描述
从键盘接收有向图的顶点集,弧集,创建有向图,并完成下列任务:
(1)计算结点的出度、入度以及度;
(2) 从第一个顶点出发,求一个深度优先遍历序列;
(3) 从第一个顶点顶点出发,求一个广度优先遍历序列。
注意:以用户输入各个顶点的顺序为顶点的序号。
在深度和广度优先遍历中,优先选择序号小的顶点。
输入
第一行输入两个整数,以空格隔开,分别代表图的顶点数n和弧数e。(顶点个数<=20)
第二行依次输入顶点值,类型为字符,中间不用间隔符。
接下去有e行,每行为两个字符 uv(中间没有间隔符),表示一条弧<u,v>。
输出
连续输出n行,依次为各个结点的出度和入度,格式为【顶点w 出度值 入度值 度值】,四者间用空格隔开。
接下去的一行,输出深度优先遍历顶点序列(顶点间无间隔符)。
最后一行,输出广度优先遍历顶点序列(顶点间无间隔符)。
样例输入
5 7
ABCDE
AB
AE
BC
CD
DA
DB
EC
样例输出
A 2 1 3
B 1 2 3
C 1 2 3
D 2 1 3
E 1 1 2
ABCDE
ABECD
代码展示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXVEX 20
#define MAX 100
typedef struct {
int adM[MAXVEX][MAXVEX];
char vertex[MAXVEX];
int vertexNum, sideNum;
}AdjMatrix;
typedef struct {
int data[MAX];
int front, rear;
}SeqQueue;
void InitQueue(SeqQueue *sq) {
sq->front = sq->rear = -1;
}
int IsEmpty(SeqQueue *sq) {
if (sq->rear == sq->front)
return 1;
return 0;
}
int EnterQueue(SeqQueue *sq, int x) {
if (sq->rear == MAX-1) {
return 0;
}
else {
sq->rear = (sq->rear+1)%MAX;
sq->data[sq->rear] = x;
return 1;
}
}
int OutQueue(SeqQueue *sq, int *x) {
if(sq->rear == sq->front)
return 0;
else {
sq->front = (sq->front+1)%MAX;
*x = sq->data[sq->front];
return 1;
}
}
int book1[MAXVEX];
int LocateVex(AdjMatrix *G, char ch) {
int i;
for (i = 0; i < G->vertexNum; i++) {
if (G->vertex[i] == ch)
return i+1;
}
return 0;
}
void CrtAdjMatrix(AdjMatrix *G) {
//printf("Please input the vertexNum and sideNum\n");
scanf("%d%d", &G->vertexNum, &G->sideNum);
for (int i = 1; i <= G->vertexNum; i++) {
for (int j = 1; j <= G->vertexNum; j++) {
G->adM[i][j] = 0;
}
}
//printf("Please input the vertex one by one\n");
scanf("%s", G->vertex);
//printf("Please input the side\n");
for (int i = 1; i <= G->sideNum; i++) {
getchar();
char vex1, vex2;
scanf("%c" , &vex1);
scanf("%c" , &vex2);
int row = LocateVex(G, vex1);
int col = LocateVex(G, vex2);
G->adM[row][col] = 1;
}
}
void AllDegree(AdjMatrix *G, char ch) {
int flag;
int cnt1 = 0, cnt2 = 0, cnt = 0;
for (int i = 0; i < G->vertexNum; i++) {
if (G->vertex[i] == ch) {
flag = i + 1;
break;
}
}
for (int i = 1; i <= G->vertexNum; i++) {
if (G->adM[flag][i] == 1) {
cnt1++;
}
if (G->adM[i][flag] == 1) {
cnt2++;
}
}
cnt = cnt1 + cnt2;
printf("%c %d %d %d\n", ch, cnt1, cnt2, cnt);
}
void DFS(AdjMatrix *G, int n) {
printf("%c", G->vertex[n-1]);
book1[n] = 1;
for (int i = 1; i <= G->vertexNum; i++) {
if (book1[i] == 0 && G->adM[n][i] == 1 )
DFS(G, i);
}
}
int book2[MAXVEX];
void BFS(AdjMatrix *G, int n) {
SeqQueue Q;
InitQueue(&Q);
printf("%c", G->vertex[n-1]);
book2[n] = 1;
EnterQueue(&Q, n);
while (!IsEmpty(&Q)) {
OutQueue(&Q, &n);
for (int i = 1; i <= G->vertexNum; i++) {
if (book2[i] == 0 && G->adM[n][i] == 1) {
printf("%c", G->vertex[i-1]);
book2[i] = 1;
EnterQueue(&Q, i);
}
}
}
}
int main(void) {
AdjMatrix G;
CrtAdjMatrix(&G);
for (int i = 0; i < G.vertexNum; i++) {
AllDegree(&G, G.vertex[i]);
}
DFS(&G, 1);
printf("\n");
BFS(&G,1);
return 0;
}