C语言编写程序实现深度优先搜索和广度优先搜索算法
时间: 2024-04-30 07:20:02 浏览: 31
深度优先搜索算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int visited[MAX];
int graph[MAX][MAX];
int n, start;
void dfs(int node) {
printf("%d ", node);
visited[node] = 1;
for (int i = 1; i <= n; i++) {
if (graph[node][i] == 1 && visited[i] == 0) {
dfs(i);
}
}
}
int main() {
printf("Enter the number of nodes: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting node: ");
scanf("%d", &start);
printf("DFS Traversal: ");
dfs(start);
return 0;
}
```
广度优先搜索算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int visited[MAX];
int graph[MAX][MAX];
int queue[MAX];
int front = -1, rear = -1;
int n, start;
void bfs(int node) {
printf("%d ", node);
visited[node] = 1;
queue[++rear] = node;
while (front != rear) {
int u = queue[++front];
for (int i = 1; i <= n; i++) {
if (graph[u][i] == 1 && visited[i] == 0) {
printf("%d ", i);
visited[i] = 1;
queue[++rear] = i;
}
}
}
}
int main() {
printf("Enter the number of nodes: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting node: ");
scanf("%d", &start);
printf("BFS Traversal: ");
bfs(start);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)