1) BFS
Breadth-First search: Given source node s, generate breadth-first search tree
The simple path from node s to node V in the breadth-first search tree corresponds to the shortest path from S to V (the path with the least number of edges)
Breadth first: The boundary between the discovered node and the uncovered node (the gray node) expands outwards along its breadth
1#include <stack>2#include <vector>3#include <queue>4#include <algorithm>5 6 using namespacestd;7 #defineINF 999999998 #defineNIL-19 intN;Ten intg[ +][ +]; One structNode A { - intcolor; - intD//Distance the intPi//Pi,ancestor -}t[ +]; -queue<int>Q; - + voidBFS (ints) - { + for(intI=0; i<n;i++) A { at if(i!=s) - { -T[i].color =0; -T[I].D =INF; -T[i].pi =NIL; - } in } -T[s].color =1; toT[S].D =0; +T[s].pi =NIL; - Q.push (s); the while(!q.empty ()) * { $ intU =Q.front ();Panax Notoginseng Q.pop (); - for(intv=0; v<n;v++) the { + if((g[u][v] = =1) && (U! =v)) A { the if(T[v].color = =0) + { -T[v].color =1; $T[V].D = T[u].d +1; $T[v].pi =u; - Q.push (v); - } the } - }WuyiT[u].color =1; the } - } Wu - /* About int main () $ { - While (cin>>n) - { - for (int i=0;i<n;i++) A { + for (int j=0;j<n;j++) the { - cin>>g[i][j]; $ } the } the int s; the cin>>s; the BFS (s); - for (int i=0;i<n;i++) in { the cout<<i<< "" <<t[i].d<< "" <<t[i].pi<<endl; the } About } the return 0; the } the */
Graph algorithm (a)--basic graph algorithm (BFS,DFS and its application) (1)