BFS算法的实现

今天我写了一个BFS(广度优先搜索)算法的程序,在此展示出来。

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <vector>
  4 #include <queue>
  5 using namespace std;
  6 
  7 const int max_dist=9999;
  8 const int invalid_p=-1;
  9 
 10 struct adjNode{
 11     int node;
 12     struct adjNode *next;
 13 };
 14 
 15 enum Color{w, g, b};
 16 
 17 struct BFS_struct{
 18     Color color;
 19     int d;
 20     int parent;
 21 };
 22 
 23 /*图的矩阵表示向邻接表表示的转换*/
 24 void matrixToAdjlist(int *matrix, adjNode *adjList, int n){
 25     int i, j;
 26     adjNode *tempNode;
 27     for(i=0; i<n; ++i){
 28         adjList[i].node=i;
 29         adjList[i].next=NULL;
 30 
 31         for(j=n-1; j>=0; j--){
 32             if(*(matrix+i*n+j)== 1){
 33                 tempNode=(adjNode *)malloc(sizeof(adjNode));
 34                 tempNode->next=adjList[i].next;
 35                 tempNode->node=j;
 36                 adjList[i].next=tempNode;
 37             }
 38         }
 39     }
 40 }
 41 
 42 /*释放邻接表中分配的空间*/
 43 void freeAdjList(adjNode *adjList, int n){
 44     int i;
 45     adjNode *tempNode;
 46 
 47     for(i=0; i<n; ++i){
 48         tempNode=adjList[i].next;
 49         while(tempNode != NULL){
 50             adjList[i].next=tempNode->next;
 51             free(tempNode);
 52             tempNode=adjList[i].next;
 53         }
 54     }
 55 
 56     free(adjList);
 57 }
 58 
 59 /*BFS算法*/
 60 void BFS(adjNode *adjList, BFS_struct *bfsArray, int s, int n){
 61     int i, temp1, temp2;
 62     adjNode *tempNode;
 63     //vector<int> bfsQueue;
 64     queue<int> bfsQueue;
 65     for(i=0; i<n; ++i){
 66         bfsArray[i].color=w;
 67         bfsArray[i].d=max_dist;
 68         bfsArray[i].parent=invalid_p;
 69     }
 70     bfsArray[s].color=g;
 71     bfsArray[s].d=0;
 72     bfsArray[s].parent=invalid_p;
 73 
 74     bfsQueue.push(s);
 75     while(!bfsQueue.empty()){
 76        temp1=bfsQueue.front();
 77        bfsQueue.pop();
 78        tempNode=adjList[temp1].next;
 79        while(tempNode != NULL){
 80            temp2=tempNode->node;
 81            if(bfsArray[temp2].color == w){
 82                bfsArray[temp2].color=g;
 83                bfsArray[temp2].d=bfsArray[temp1].d+1;
 84                bfsArray[temp2].parent=temp1;
 85                bfsQueue.push(temp2);
 86            }
 87 
 88            tempNode=tempNode->next;
 89        }
 90 
 91        bfsArray[temp1].color=b;
 92     }
 93 
 94 }
 95 
 96 /*输出BFS学习之后从源节点s到各个节点的最短路径*/
 97 void print_path(BFS_struct *bfsArray, int s, int u){
 98     if(s == u)
 99         printf("%d ", s);
100     else if(bfsArray[u].parent == invalid_p)
101         printf("There is no path form %d to %d", s, u);
102     else{
103         print_path(bfsArray, s, bfsArray[u].parent);
104         printf("%d ", u);
105     }
106 }
107 
108 int main(){
109     int *matrix;
110     adjNode *adjList, *tempNode;
111     int nodeNum=0, i, j, startpoint=0;
112     BFS_struct *bfsArray;
113 
114     printf("Input node number: ");
115     scanf("%d", &nodeNum);
116 
117     matrix=(int *)malloc(sizeof(int)*nodeNum*nodeNum);
118     adjList=(adjNode *)malloc(sizeof(adjNode)*nodeNum);
119 
120     for(i=0; i<nodeNum; ++i)
121         for(j=0; j<nodeNum; ++j)
122             scanf("%d", matrix+i*nodeNum+j);
123 
124     /*以矩阵形式输出图*/
125     printf("matrix: \n");
126     for(i=0; i<nodeNum; ++i){
127         for(j=0; j<nodeNum; ++j)
128             printf("%d ", *(matrix+i*nodeNum+j));
129         printf("\n");
130     }
131 
132     matrixToAdjlist(matrix, adjList, nodeNum);
133     /*以邻接表形式输出图*/
134     printf("adjacency list: \n");
135     for(i=0; i<nodeNum; ++i){
136         printf("node %d:", adjList[i].node);
137         tempNode=adjList[i].next;
138         while(tempNode != NULL){
139             printf("->%d", tempNode->node);
140             tempNode=tempNode->next;
141         }
142         printf("\n");
143     }
144 
145     printf("Please intput startpoint: ");
146     scanf("%d", &startpoint);
147     bfsArray=(BFS_struct *)malloc(sizeof(BFS_struct)*nodeNum);
148     BFS(adjList, bfsArray, startpoint, nodeNum);
149     for(i=0; i<nodeNum; ++i){
150         printf("path form %d to %d: ", startpoint, i);
151         print_path(bfsArray, startpoint, i);
152         printf("\n");
153     }
154 
155     free(matrix);
156     free(bfsArray);
157     freeAdjList(adjList, nodeNum);
158     return 0;
159 }

在程序中,我把图的表示方式(邻接矩阵和邻接表)与BFS算法用到的数据结构(主要是BFS_struct)分离开来,没有把BFS_struct写到adjList中,主要是考虑到邻接矩阵和邻接表的通用性。在别的程序中matrixToAdjlist()函数也可使用,但是BFS_struct数据结构就不一定能用得到(例如DFS算法)。其实把图的表示方式和matrixToAdjlist()函数这一部分应该拿出来单独写在一个独立的头文件中,这样每当写关于图的程序时都可以引用该头文件。

 
 
 
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: DFS(深度优先搜索)和BFS(广度优先搜索)算法是图论中常见的两种算法,用于遍历图或树的节点。以下是C++实现: DFS算法实现: ```c++ #include <iostream> #include <vector> #include <stack> using namespace std; void dfs(vector<vector<int>>& graph, vector<bool>& visited, int start) { stack<int> s; s.push(start); while (!s.empty()) { int node = s.top(); s.pop(); if (!visited[node]) { visited[node] = true; cout << node << " "; for (int i = graph[node].size() - 1; i >= 0; --i) { int next_node = graph[node][i]; if (!visited[next_node]) { s.push(next_node); } } } } } int main() { int n = 5; vector<vector<int>> graph(n); graph[0].push_back(1); graph[0].push_back(2); graph[1].push_back(3); graph[1].push_back(4); vector<bool> visited(n, false); dfs(graph, visited, 0); return 0; } ``` BFS算法实现: ```c++ #include <iostream> #include <vector> #include <queue> using namespace std; void bfs(vector<vector<int>>& graph, vector<bool>& visited, int start) { queue<int> q; q.push(start); while (!q.empty()) { int node = q.front(); q.pop(); if (!visited[node]) { visited[node] = true; cout << node << " "; for (int i = 0; i < graph[node].size(); ++i) { int next_node = graph[node][i]; if (!visited[next_node]) { q.push(next_node); } } } } } int main() { int n = 5; vector<vector<int>> graph(n); graph[0].push_back(1); graph[0].push_back(2); graph[1].push_back(3); graph[1].push_back(4); vector<bool> visited(n, false); bfs(graph, visited, 0); return 0; } ``` 这里我们以一个简单的无向图为例,节点从0到4编号,图的邻接表表示为: ``` 0: 1, 2 1: 0, 3, 4 2: 0 3: 1 4: 1 ``` DFS算法BFS算法的输出结果都是:0 2 1 4 3。 ### 回答2: DFS(深度优先搜索)和BFS(广度优先搜索)是两种常用的图遍历算法,都可以用来实现C语言。 DFS算法通过递归或者栈的方式实现,可以从图的某个顶点开始,沿着一条路径一直到达没有未探索的邻居节点为止,然后返回到前一个顶点继续探索其他未探索的邻居节点。可以用以下C语言代码实现DFS算法: ```c #include <stdio.h> #define SIZE 100 int visited[SIZE]; //用来标记节点是否访问过 int graph[SIZE][SIZE]; //图的邻接矩阵表示 void dfs(int node) { printf("%d ", node); visited[node] = 1; for(int i = 0; i < SIZE; i++) { if(graph[node][i] && !visited[i]) { dfs(i); } } } int main() { //初始化visited和graph //调用dfs函数 dfs(0); //从节点0开始深度优先搜索 return 0; } ``` BFS算法通过队列的方式实现,可以从图的某个顶点开始,将其加入队列,然后依次将队列中的节点访问并将其邻居节点加入队列,直到队列为空。可以用以下C语言代码实现BFS算法: ```c #include <stdio.h> #define SIZE 100 int visited[SIZE]; //用来标记节点是否访问过 int graph[SIZE][SIZE]; //图的邻接矩阵表示 void bfs(int node) { int queue[SIZE]; int front = 0, rear = 0; queue[rear++] = node; visited[node] = 1; while(front < rear) { int curNode = queue[front++]; printf("%d ", curNode); for(int i = 0; i < SIZE; i++) { if(graph[curNode][i] && !visited[i]) { queue[rear++] = i; visited[i] = 1; } } } } int main() { //初始化visited和graph //调用bfs函数 bfs(0); //从节点0开始广度优先搜索 return 0; } ``` 以上就是用C语言实现DFS和BFS算法代码。在实际应用中,可以根据具体场景选择使用DFS还是BFS来进行图的遍历。 ### 回答3: DFS(深度优先搜索)和BFS(广度优先搜索)算法都是用于图的遍历的常见算法。它们在图遍历的顺序、搜索方式和空间复杂度上有所差异。 DFS是一种先深入后回溯的搜索方法。它从起点开始,沿着图的一条路径一直遍历到尽头,然后回溯到上一个节点,继续探索其他未遍历的路径,直到整个图都被遍历完。DFS常用递归或栈的方式实现BFS是一种逐层扩展的搜索方法。它从起点开始,首先遍历起点的所有邻接节点,然后依次遍历邻接节点的邻接节点,以此类推,直到整个图都被遍历完。BFS常用队列的方式实现,每次将待遍历节点加入队列,并在从队列中取出节点时,将其邻接节点加入队列。 在C语言中,实现DFS和BFS算法可以借助图的表示方式和遍历的数据结构。一种常见的图的表示方式是邻接矩阵或邻接表,用于存储图的顶点和边的关系。而在遍历过程中,可以借助一个访问标记数组,用于标记节点是否被访问过。 对于DFS算法实现,可以通过递归函数实现,递归函数的参数包括当前遍历的节点、访问标记数组等。递归函数的主体部分可以按照DFS的逻辑进行实现。 而对于BFS算法实现,可以通过队列来实现,首先将起点加入队列,然后循环取出队列中的节点,并将其邻接节点依次加入队列,直到队列为空。在每次取出节点时,可以将其标记为已经访问过。 总之,DFS和BFS算法在C语言中的实现需要借助图的表示方式,以及递归函数或队列等数据结构。具体实现的细节还可以根据具体问题的需求进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值