广度优先遍历BFS

本文章代码中的图用邻接矩阵来表示,所以算法复杂度为O(V^2)。

如果用邻接表来表示,那么算法的复杂度为O(V+E)。

 

献上代码:

#include <iostream> #include <queue> #include <climits> #define MAXLENGTH 1000 #define WHITE false #define BLACK true using namespace std; //the color of node i bool color[MAXLENGTH]; //the parent of node i int Parent[MAXLENGTH]; //the distance from i to start int Distance[MAXLENGTH]; //the node graph int Graph[MAXLENGTH][MAXLENGTH]; void BFS(int s, int n) { queue<int> Queue; for (int i = 0; i < n; ++i) { color[i] = WHITE; Parent[i] = -1; Distance[i] = INT_MAX; } color[s] = BLACK; Distance[s] = 0; Queue.push(s); while (!Queue.empty()) { int from = Queue.front(); Queue.pop(); for (int i = 0; i < n; ++i) { if (Graph[from][i] == 1 && color[i] == WHITE) { color[i] = BLACK; Parent[i] = from; Distance[i] = Distance[from] + 1; Queue.push(i); } } } } /** * @brief Print the path from start to end * * @param end: the end node */ void PrintPath(int end) { cout << "The distance is " << Distance[end] << ". Show path from end to start" << endl; while (end != -1) { cout << end << " "; end = Parent[end]; } cout << endl; } int main() { int n; while (cin >> n, n != 0) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cin >> Graph[i][j]; } } cout << "Input the start node, from 0->n-1" << endl; int start; int end; cin >> start; BFS(start, n); while (cout << "Input the end node, -1 means no more search." << endl, cin >> end, end != -1) { PrintPath(end); } } }

你可能感兴趣的:(算法,Graph,input,Path,distance)