写一段c++ 广度优先搜索的代码
时间: 2023-02-20 19:40:10 浏览: 17
好的,下面是一段用 C 语言实现的广度优先搜索代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 100
#define MAX_NEIGHBORS 100
int n; // number of nodes
int m; // number of edges
int adjacency_matrix[MAX_NODES][MAX_NEIGHBORS]; // adjacency matrix to store the graph
int visited[MAX_NODES]; // an array to keep track of the visited nodes
void breadth_first_search(int start) {
int queue[MAX_NODES]; // a queue to store the next node to be visited
int head = 0; // the head of the queue
int tail = 0; // the tail of the queue
int current_node; // the current node being processed
int i; // loop variable
// initialize all nodes as not visited
for (i = 0; i < n; i++) {
visited[i] = 0;
}
// mark the starting node as visited
visited[start] = 1;
queue[tail] = start;
tail++;
// continue searching until the queue is empty
while (head < tail) {
current_node = queue[head];
head++;
for (i = 0; i < m; i++) {
if (adjacency_matrix[current_node][i] == 1 && visited[i] == 0) {
visited[i] = 1;
queue[tail] = i;
tail++;
}
}
}
}
int main() {
int i, j; // loop variables
int start; // the starting node for the search
// read the number of nodes and edges
scanf("%d %d", &n, &m);
// read the adjacency matrix
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
scanf("
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)