一、广度优先算法BFS(Breadth First Search)
基本实现思想
(1)顶点v入队列。
(2)当队列非空时则继续执行,否则算法结束。
(3)出队列取得队头顶点v;
(4)查找顶点v的所以子节点,并依次进入队列;
(5)转到步骤(2)。
二、深度优先算法DFS(Depth First Search)
基本思想:
递归实现:
(1)访问顶点v,打印节点;
(2)遍历v的子节点w,while(w存在),递归执行该节点;
代码:
/布尔型数组Visited[]初始化成false void DFS(Vetex v) { Visited[v] = true; for each w adjacent to v if (!Visited[w]) DFS(w); }
非递归实现:
(1)访问顶点v,顶点v入栈S,打印输出顶点,visited[v]=1
(2)while(栈S非空)
x=栈S的顶元素(不出栈);
if(存在并找到未被访问的x的子结点w)
访问w,打印输出,visited[w]=1;w进栈;
else
x出栈;
注:visited[x]=1,标记该节点已被访问
1 #include<iostream> 2 #include<queue> 3 #include<stack> 4 #include<vector> 5 using namespace std; 6 const int MAX = 10; 7 typedef struct graph 8 { 9 int n;//顶点个数 10 int e;//边数 11 int edge[MAX][MAX];//邻接矩阵 12 }Graph; 13 vector<bool> visited(MAX,0); 14 void InitGraph(Graph *G) 15 { 16 for (int i = 0; i < MAX; i++) 17 for (int j = 0; j < MAX; j++) 18 G->edge[i][j] = 0; 19 } 20 21 //广度优先遍历,num是从哪个结点开始 22 void BFS(Graph G,int num) 23 { 24 queue<int> q; 25 cout << num << " "; 26 visited[num] = true; 27 q.push(num); 28 while (!q.empty()) 29 { 30 int temp = q.front(); 31 q.pop(); 32 for (int i = 0; i < G.n; i++) 33 { 34 if (G.edge[temp][i] != 0 && visited[i] == false) 35 { 36 q.push(i); 37 cout << i << " "; 38 visited[i] = true; 39 } 40 } 41 } 42 cout << endl; 43 } 44 45 //深度优先遍历的递归版本 46 void DFS1(graph G,int num) 47 { 48 visited[num] = true; 49 cout << num << " "; 50 for (int i = 0; i < G.n; i++) 51 { 52 if (G.edge[num][i] != 0 && visited[i] == false) 53 DFS1(G,i); 54 } 55 } 56 57 //深度优先非递归版本 58 void DFS2(graph G,int num) 59 { 60 stack<int> s; 61 s.push(num); 62 visited[num] = true; 63 while (!s.empty()) 64 { 65 int temp = s.top(); 66 s.pop(); 67 cout << temp<<" "; 68 for (int i = G.n - 1; i >= 0; i--) 69 { 70 if (G.edge[temp][i] != 0 && visited[i] == false) 71 { 72 s.push(i); 73 visited[i] = true; 74 } 75 } 76 } 77 cout << endl; 78 } 79 80 int main() 81 { 82 int a, b, v, i; 83 Graph G; 84 cin >> G.n >> G.e; //n,e为顶点个数,边个数 85 InitGraph(&G); //对G进行初始化,整个MAX范围初始化 86 for (i = 0; i < G.e; i++) //建图 87 { 88 cin >> a >> b >> v; //a,b为顶点,v为权值 89 G.edge[a][b] = v; 90 G.edge[b][a] = v; 91 } 92 BFS(G, 0); //0为开始搜索的顶点序号 93 for (i = 0; i < MAX; i++) 94 visited[i] = 0; 95 DFS1(G, 0); 96 cout << endl; 97 for (i = 0; i < MAX; i++) 98 visited[i] = 0; 99 DFS2(G, 0); 100 return 0; 101 }