邻接表的深搜广搜c语言
时间: 2023-12-18 12:28:38 浏览: 187
C语言数据结构-邻接表的广度优先遍历
邻接表是一种图的存储结构,它可以用于实现图的深度优先搜索(DFS)和广度优先搜索(BFS)。下面是邻接表的深搜和广搜的C语言实现:
1. 邻接表的深度优先搜索(DFS)C语言实现:
```c
#define MAXNODE 1000
#define MAXSIDE 10000
typedef struct SIDE {
int tailNode;
int nextSide;
int weight;
} SIDE;
SIDE edge[MAXSIDE];
int head[MAXNODE];
int visited[MAXNODE];
int counttEdge = 0;
void CreateABoundary(int headNode, int tailNode, int weight) {
edge[counttEdge].tailNode = tailNode;
edge[counttEdge].weight = weight;
edge[counttEdge].nextSide = head[headNode];
head[headNode] = counttEdge;
counttEdge++;
}
void DFS(int node) {
visited[node] = 1;
printf("%d ", node);
for (int i = head[node]; i != -1; i = edge[i].nextSide) {
int nextNode = edge[i].tailNode;
if (!visited[nextNode]) {
DFS(nextNode);
}
}
}
int main() {
// 初始化
memset(head, -1, sizeof(head));
memset(visited, 0, sizeof(visited));
counttEdge = 0;
// 创建图
CreateABoundary(1, 2, 0);
CreateABoundary(1, 3, 0);
CreateABoundary(2, 4, 0);
CreateABoundary(2, 5, 0);
CreateABoundary(3, 6, 0);
CreateABoundary(3, 7, 0);
// DFS遍历
DFS(1);
return 0;
}
```
2. 邻接表的广度优先搜索(BFS)C语言实现:
```c
#define MAXNODE 1000
#define MAXSIDE 10000
typedef struct SIDE {
int tailNode;
int nextSide;
int weight;
} SIDE;
SIDE edge[MAXSIDE];
int head[MAXNODE];
int visited[MAXNODE];int counttEdge = 0;
void CreateABoundary(int headNode, int tailNode, int weight) {
edge[counttEdge].tailNode = tailNode;
edge[counttEdge].weight = weight;
edge[counttEdge].nextSide = head[headNode];
head[headNode] = counttEdge;
counttEdge++;
}
void BFS(int node) {
int queue[MAXNODE];
int front = 0, rear = 0;
visited[node] = 1;
printf("%d ", node);
queue[rear++] = node;
while (front < rear) {
int curNode = queue[front++];
for (int i = head[curNode]; i != -1; i = edge[i].nextSide) {
int nextNode = edge[i].tailNode;
if (!visited[nextNode]) {
visited[nextNode] = 1;
printf("%d ", nextNode);
queue[rear++] = nextNode;
}
}
}
}
int main() {
// 初始化
memset(head, -1, sizeof(head));
memset(visited, 0, sizeof(visited));
counttEdge = 0;
// 创建图
CreateABoundary(1, 2, 0);
CreateABoundary(1, 3, 0);
CreateABoundary(2, 4, 0);
CreateABoundary(2, 5, 0);
CreateABoundary(3, 6, 0);
CreateABoundary(3, 7, 0);
// BFS遍历
BFS(1);
return 0;
}
```
阅读全文