用c语言编写深度优先搜索和广度优先探索的代码
时间: 2023-10-21 15:00:48 浏览: 77
以下是用 C 语言编写深度优先搜索和广度优先探索的示例代码。
深度优先搜索代码:
```c
#include <stdio.h>
#define MAX_VERTICES 50
int visited[MAX_VERTICES];
int adj[MAX_VERTICES][MAX_VERTICES];
int n;
void dfs(int v)
{
int i;
visited[v] = 1;
printf("%d ", v);
for (i = 0; i < n; i++)
if (adj[v][i] && !visited[i])
dfs(i);
}
int main()
{
int i, j;
printf("Enter number of vertices:");
scanf("%d", &n);
printf("\nEnter adjecency matrix of the graph:\n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &adj[i][j]);
for (i = 0; i < n; i++)
visited[i] = 0;
printf("Depth First Search Traversal:\n");
for (i = 0; i < n; i++)
if (!visited[i])
dfs(i);
return 0;
}
```
广度优先探索代码:
```c
#include <stdio.h>
#define MAX_VERTICES 50
int visited[MAX_VERTICES];
int adj[MAX_VERTICES][MAX_VERTICES];
int queue[MAX_VERTICES];
int front = -1, rear = -1;
int n;
void enqueue(int v)
{
if (rear == MAX_VERTICES - 1)
printf("Queue Overflow\n");
else
{
if (front == -1)
front = 0;
rear++;
queue[rear] = v;
}
}
int dequeue()
{
int del_item;
if (front == -1 || front > rear)
{
printf("Queue Underflow\n");
return -1;
}
else
{
del_item = queue[front];
front++;
return del_item;
}
}
void bfs(int v)
{
int i, cur_vertex;
visited[v] = 1;
printf("%d ", v);
enqueue(v);
while (front != -1)
{
cur_vertex = dequeue();
for (i = 0; i < n; i++)
{
if (adj[cur_vertex][i] && !visited[i])
{
visited[i] = 1;
printf("%d ", i);
enqueue(i);
}
}
}
}
int main()
{
int i, j;
printf("Enter number of vertices:");
scanf("%d", &n);
printf("\nEnter adjecency matrix of the graph:\n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &adj[i][j]);
for (i = 0; i < n; i++)
visited[i] = 0;
printf("Breadth First Search Traversal:\n");
for (i = 0; i < n; i++)
if (!visited[i])
bfs(i);
return 0;
}
```
阅读全文