c语言邻接矩阵bfs和dfs
时间: 2023-12-11 17:32:56 浏览: 124
数据结构课程设计
以下是C语言中邻接矩阵实现的BFS和DFS算法的示例代码:
BFS算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MaxInt 32767
#define MVNum 100
typedef char VerTexType;
typedef int ArcType;
typedef struct {
VerTexType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum, arcnum;
} AMGraph;
int visited[MVNum];
void BFS(AMGraph G, int v) {
int queue[MVNum], front = 0, rear = 0;
int i, j, w;
printf("%c ", G.vexs[v]);
visited[v] = 1;
queue[rear++] = v;
while (front != rear) {
i = queue[front++];
for (j = 0; j < G.vexnum; j++) {
if (G.arcs[i][j] != MaxInt && !visited[j]) {
printf("%c ", G.vexs[j]);
visited[j] = 1;
queue[rear++] = j;
}
}
}
}
int main() {
AMGraph G;
int i, j;
printf("请输入顶点数和边数:");
scanf("%d%d", &G.vexnum, &G.arcnum);
printf("请输入顶点信息:");
for (i = 0; i < G.vexnum; i++) {
scanf("%c", &G.vexs[i]);
}
printf("请输入邻接矩阵:");
for (i = 0; i < G.vexnum; i++) {
for (j = 0; j < G.vexnum; j++) {
scanf("%d", &G.arcs[i][j]);
if (G.arcs[i][j] == 0) {
G.arcs[i][j] = MaxInt;
}
}
}
printf("请输入遍历起点:");
int v;
scanf("%d", &v);
printf("BFS遍历结果:");
BFS(G, v);
return 0;
}
```
DFS算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MaxInt 32767
#define MVNum 100
typedef char VerTexType;
typedef int ArcType;
typedef struct {
VerTexType vexs[MVNum];
ArcType arcs[MVNum][MVNum];
int vexnum, arcnum;
} AMGraph;
int visited[MVNum];
void DFS(AMGraph G, int v) {
int i;
printf("%c ", G.vexs[v]);
visited[v] = 1;
for (i = 0; i < G.vexnum; i++) {
if (G.arcs[v][i] != MaxInt && !visited[i]) {
DFS(G, i);
}
}
}
int main() {
AMGraph G;
int i, j;
printf("请输入顶点数和边数:");
scanf("%d%d", &G.vexnum, &G.arcnum);
printf("请输入顶点信息:");
for (i = 0; i < G.vexnum; i++) {
scanf("%c", &G.vexs[i]);
}
printf("请输入邻接矩阵:");
for (i = 0; i < G.vexnum; i++) {
for (j = 0; j < G.vexnum; j++) {
scanf("%d", &G.arcs[i][j]);
if (G.arcs[i][j] == 0) {
G.arcs[i][j] = MaxInt;
}
}
}
printf("请输入遍历起点:");
int v;
scanf("%d", &v);
printf("DFS遍历结果:");
DFS(G, v);
return 0;
}
```
阅读全文