- 在实现了二叉树的深door和广door优先遍历后,我们再来看看对于图怎么遍历,首先我们定义图节点,每个节点都有它的nextdoors,把它们都存在矩阵里,以及用来实现广度优先遍历的队列结构体
#define NUM 30
typedef struct graNode {
char nodeValue[NUM];//图的顶点信息
int relation[NUM][NUM];//图的邻接矩阵表示
int nodeNum=0;//图的顶点数
int edgeNum=0;//图的边数
}graNode,*graph;
typedef struct qnode {
int data;//顶点编号
struct qnode* next;
}qnode;
typedef struct listNode {
qnode* head;
qnode* rear;
}listNode,*qlist;
- 图的初始化
void initGraph(graph G) {
for (int i = 0; i < NUM; i++)
mark[i] = 0;
for (int i = 0; i < NUM; i++)
for (int j = 0; j < NUM; j++)
G->relation[i][j] = 0;
cout << "输入图的节点个数" << endl;
cin >> G->nodeNum;
cout << "输入图的所有节点值" << endl;
for (int i = 0; i < G->nodeNum; i++) {
cin >> G->nodeValue[i];
}
cout << "输入边的个数" << endl;
cin >> G->edgeNum;
cout << "输入有关系的节点编号,两两相隔" << endl;
int j, k;
for (int i = 0; i < G->edgeNum; i++) {
cin >> j >> k;
G->relation[j][k] = 1;
}
}
- 先让起始遍历顶点进队列,然后取出这个点并输出,如果它有临接节点,就让邻接节点进队列,重复上述步骤(取出节点,邻接节点进队列)
void bfs(graph G) {
if (G->nodeNum == 0) {
cout << "图不存在" << endl;
return;
}
qlist Q = new listNode;
Q->head = Q->rear = NULL;//初始化队列
enterQueue(Q, 2);//起始节点进队列,2是起始节点值在数组中的下标
while (Q->head) {
leaveQueue(Q,G->relation,G->nodeValue);//重复执行节点出队列,邻接节点进队列,直到节点为空
}
}
//进队列
void enterQueue(qlist Q, int data) {
qnode* node = new qnode;
node->data = data;
node->next = NULL;
if (Q->head ==NULL)
Q->head = node;
if (Q->rear == NULL)
Q->rear = node;
else {
Q->rear->next = node;
Q->rear = node;
}
}
//出队列,如果有邻接节点,就让邻接节点进队列
void leaveQueue(qlist Q,int relation[NUM][NUM],char value[NUM]) {
cout << value[Q->head->data] << endl;
int nodeId = Q->head->data;
mark[nodeId] = 1;//标记为已经访问
Q->head = Q->head->next;
if (Q->head == NULL)
Q->rear = NULL;
for (int i = 0; i < NUM; i++) {
if (mark[i] == 0 && relation[nodeId][i] == 1)
enterQueue(Q, i);
}
}
4.深度优先遍历同上述,只是把队列换成了栈
5.最后是我们的main函数
int main() {
graph G = new graNode;
initGraph(G);
bfs(G);
}
6.测试结果