<C/C++图>搜索算法:DFS与BFS

一,图的遍历基本理论

首先定义图的遍历(Traversing Graph):指从图中某一顶点出发访问图中其余顶点,且使每个顶点仅被访问一次。有两种常用的方法可用来搜索图:即深度优先搜索和广度优先搜索。它们最终都会到达所有连通的顶点。深度优先搜索通过栈来实现,而广度优先搜索通过队列来实现。

1,深度优先图搜索

DFS,Depth-First-Search)

下面图中的动态图显示了深度优先搜索顶点被访问的顺序。




为了实现深度优先搜索,首先选择一个起始顶点并需要遵守三个规则:
(1) 如果可能,访问一个邻接的未访问顶点,标记它,并把它放入栈中。
(2) 当不能执行规则1时,如果栈不空,就从栈中弹出一个顶点。
(3) 如果不能执行规则1和规则2,就完成了整个搜索过程。

伪代码: 

[html]  view plain  copy
 print ?
  1. <span style="font-family:Times New Roman;font-size:18px;">procedure dfs(vertex v)  
  2. {  
  3.     mark v as visited //标记顶点为已访问    
  4.     for each w adjacent to v //将邻顶点变成新的当前顶点    
  5.     {  
  6.         if w unvisited//若这个新的当前节点没有被访问过    
  7.         {  
  8.             dfs(w) //递归调用    
  9.         }  
  10.     }  
  11. }</span>  


2,广度优先图搜索

BFS,Breadth First Search

在深度优先搜索中,算法表现得好像要尽快地远离起始点似的。相反,在广度优先搜索中,算法好像要尽可能地靠近起始点。

它首先访问起始顶点的所有邻接点,然后再访问较远的区域。它是用队列来实现的。

下面图中的数字显示了广度优先搜索顶点被访问的顺序。


实现广度优先搜索,也要遵守三个规则:
(1) 访问下一个未来访问的邻接点,这个顶点必须是当前顶点的邻接点,标记它,并把它插入到队列中。
(2) 如果因为已经没有未访问顶点而不能执行规则1时,那么从队列头取一个顶点,并使其成为当前顶点。
(3) 如果因为队列为空而不能执行规则2,则搜索结束。

伪代码:

[html]  view plain  copy
 print ?
  1. procedure BFS(vertex s)   
  2. {  
  3.   create a queue Q //创建一个队列  
  4.   enqueue s onto Q //顶点s进队  
  5.   mark s as visited //  
  6.    while Q is not empty  
  7.    {   
  8.       dequeue a vertex from Q into v  
  9.       for each w adjacent to v   
  10.        {   
  11.         if w unvisited  
  12.          {   
  13.           mark w as visited   
  14.           enqueue w onto Q   
  15.           }   
  16.        }   
  17.   }  
  18. }  

 

3,上文例图中,两者的搜索区别:

广度优先搜索顺序应该为: A-B-C-D-E-F-G      

深度优先搜索顺序应该为:A-B-E-F-D-C-G

文字描述两者区别:

广度优先每次遍历完某一个顶点的所有相邻顶点,然后再从这些相邻额顶点中在选择一个顶点作为初始顶点重复上面的过程。

二,C++模板实现

(本程序构造的是一棵树,无任何回路)

1,Graph.h的代码如下:

[cpp]  view plain  copy
 print ?
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. #include "queue"  
  4. using namespace std;  
  5.   
  6. template<class DistType/*边的权值的类型*/>   
  7. class Edge//边的定义  
  8. {  
  9. public:  
  10.     Edge(int dest, DistType weight)  
  11.     {  
  12.         m_nposTable=dest;  
  13.         m_distWeight=weight;   
  14.         m_pnext=NULL;  
  15.     }  
  16.     ~Edge()  
  17.     {  
  18.   
  19.     }  
  20. public:  
  21.     int m_nposTable;//该边的目的顶点在顶点集中的位置  
  22.     DistType m_distWeight;//边的权重值  
  23.     Edge<DistType> *m_pnext;//下一条边(注意不是下一个顶点,因为m_nposTable已经知道了这个顶点的位置)  
  24. };  
  25. //声明  
  26. template<class NameType/*顶点集名字类型*/class DistType/*距离的数据类型*/class Graph;  
  27.   
  28. template<class NameType/*顶点集名字类型*/class DistType/*距离的数据类型*/>   
  29. class Vertex//顶点的定义  
  30. {  
  31. public:  
  32.     Vertex()  
  33.     {  
  34.         padjEdge=NULL;  
  35.         m_vertexName=0;  
  36.     }  
  37.     ~Vertex()  
  38.     {  
  39.         Edge<DistType> *pmove = padjEdge;  
  40.         while (pmove)  
  41.         {  
  42.             padjEdge = pmove->m_pnext;  
  43.             delete pmove;  
  44.             pmove = padjEdge;  
  45.         }  
  46.     }  
  47.   
  48. private:  
  49.     friend class Graph<NameType,DistType>;//允许Graph类任意访问  
  50.     NameType m_vertexName;//顶点中的数据内容  
  51.     Edge<DistType> *padjEdge;//顶点的邻边  
  52.   
  53. };  
  54.   
  55.   
  56. template<class NameType/*顶点集名字类型*/class DistType/*距离的数据类型*/>   
  57. class Graph  
  58. {  
  59. public:  
  60.     Graph(int size = m_nDefaultSize/*图顶点集的规模*/)  
  61.     {  
  62.         m_pVertexTable = new Vertex<NameType, DistType>[size];  //为顶点集分配内存  
  63.         if (m_pVertexTable == NULL)  
  64.         {  
  65.             exit(1);  
  66.         }  
  67.         m_numVertexs=0;  
  68.         m_nmaxSize=size;  
  69.         m_nnumEdges=0;  
  70.     }  
  71.   
  72.     ~Graph()  
  73.     {  
  74.         Edge<DistType> *pmove;  
  75.         for (int i=0; i < this->m_numVertexs; i++)  
  76.         {  
  77.             pmove = this->m_pVertexTable[i].padjEdge;  
  78.             if (pmove){  
  79.                 this->m_pVertexTable[i].padjEdge = pmove->m_pnext;  
  80.                 delete pmove;  
  81.                 pmove = this->m_pVertexTable[i].padjEdge;  
  82.             }  
  83.         }  
  84.         delete[] m_pVertexTable;  
  85.     }  
  86.     int GetNumEdges()  
  87.     {//获得边的数目  
  88.         return m_nnumEdges/2;  
  89.     }  
  90.     int GetNumVertexs()  
  91.     {//获得顶点数目  
  92.         return m_numVertexs;  
  93.     }  
  94.   
  95.     bool IsGraphFull() const  
  96.     {     //图满的?  
  97.         return m_nmaxSize == m_numVertexs;  
  98.     }  
  99.     //在顶点集中位置为v1和v2的顶点之间插入边  
  100.     bool InsertEdge(int v1, int v2, DistType weight=m_Infinity);   
  101.     //插入顶点名字为vertex的顶点  
  102.     bool InsertVertex(const NameType vertex);    
  103.     //打印图  
  104.     void PrintGraph();     
  105.     //顶点v到其他各个顶点的最短路径(包括自身)  
  106.     void Dijkstra(int v, DistType *shotestpath);  
  107.     //获取顶点集中位置为v1和v2的顶点之间边的权重值  
  108.     DistType GetWeight(int v1, int v2);   
  109.     //获得在顶点集中的位置为v的顶点的名字  
  110.     NameType GetVertexValue(int v);  
  111.     //用该顶点的名字来寻找其在顶点集中的位置  
  112.     int GetVertexPosTable(const NameType vertex);    
  113.   
  114.   
  115.     //深度搜索优先  
  116.     void DFS(int v, int *visited);        
  117.     void DFS();  
  118.     //广度优先搜索  
  119.     void BFS(int v, int *visited);  
  120.     void BFS();  
  121.     //获取第v个顶点的名字(或者说内容)  
  122.     NameType GetVertexName(int v);     
  123.     //获得顶点v的第一个相邻顶点,如果没有就返回-1  
  124.     int GetFirst(int v);         
  125.     //获得顶点v1的邻点v2后的邻点  
  126.     int GetNext(int v1, int v2);  
  127.   
  128. private:  
  129.     Vertex<NameType, DistType> *m_pVertexTable;   //顶点集  
  130.     int m_numVertexs;//图中当前的顶点数量  
  131.     int m_nmaxSize;//图允许的最大顶点数  
  132.     static const int m_nDefaultSize = 10;       //默认的最大顶点集数目  
  133.     static const DistType m_Infinity = 65536;  //边的默认权值(可以看成是无穷大)  
  134.     int m_nnumEdges;//图中边的数目  
  135.       
  136. };  
  137.   
  138.   
  139. //返回顶点vertexname在m_pVertexTable(顶点集)中的位置  
  140. //如果不在顶点集中就返回-1  
  141. template<class NameType, class DistType>   
  142. int Graph<NameType, DistType>::GetVertexPosTable(const NameType vertexname)  
  143. {  
  144.     for (int i=0; i < this->m_numVertexs; i++)  
  145.     {  
  146.         if (vertexname == m_pVertexTable[i].m_vertexName)  
  147.         {  
  148.             return i;  
  149.         }  
  150.     }  
  151.     return -1;  
  152. }  
  153.   
  154. //打印图中的各个顶点及其链接的边的权重  
  155. template<class NameType, class DistType>   
  156. void Graph<NameType, DistType>::PrintGraph()  
  157. {  
  158.     Edge<DistType> *pmove;  
  159.     for (int i=0; i<this->m_numVertexs; i++)  
  160.     {  
  161.         cout << this->m_pVertexTable[i].m_vertexName << "->";  
  162.         pmove = this->m_pVertexTable[i].padjEdge;  
  163.         while (pmove)  
  164.         {  
  165.             cout << pmove->m_distWeight << "->" << this->m_pVertexTable[pmove->m_nposTable].m_vertexName << "->";  
  166.             pmove = pmove->m_pnext;  
  167.         }  
  168.         cout << "NULL" << endl;  
  169.     }  
  170. }  
  171. //获得在顶点集中的位置为v的顶点的名字  
  172. template<class NameType, class DistType>   
  173. NameType Graph<NameType, DistType>::GetVertexValue(int v)  
  174. {  
  175.     if (v<0 || v>=this->m_numVertexs)  
  176.     {  
  177.         cerr << "查找的顶点位置参数有误,请检查!" <<endl;  
  178.         exit(1);  
  179.     }  
  180.     return m_pVertexTable[v].m_vertexName;  
  181.   
  182. }  
  183. //返回顶点v1和v2之间的边权值,  
  184. //如果没有直接相连(即不是一条边直接相连)则返回无穷大  
  185. template<class NameType, class DistType>   
  186. DistType Graph<NameType, DistType>::GetWeight(int v1, int v2)  
  187. {  
  188.     if (v1>=0 && v1<this->m_numVertexs && v2>=0 && v2<this->m_numVertexs)  
  189.     {  
  190.         if (v1 == v2)  
  191.         {  
  192.             return 0;  
  193.         }  
  194.         Edge<DistType> *pmove = m_pVertexTable[v1].padjEdge;  
  195.         while (pmove)  
  196.         {  
  197.             if (pmove->m_nposTable == v2)  
  198.             {  
  199.                 return pmove->m_distWeight;  
  200.             }  
  201.             pmove = pmove->m_pnext;  
  202.         }  
  203.     }  
  204.       
  205.     return m_Infinity;    
  206. }  
  207.   
  208. //顶点依次插入到分配好的顶点集中  
  209. template<class NameType, class DistType>   
  210. bool Graph<NameType, DistType>::InsertVertex(const NameType vertexname)  
  211. {  
  212.     if (IsGraphFull())  
  213.     {  
  214.         cerr<<"图已经满,请勿再插入顶点!"<<endl;  
  215.         return false;  
  216.     }else  
  217.     {  
  218.         this->m_pVertexTable[this->m_numVertexs].m_vertexName = vertexname;  
  219.         this->m_numVertexs++;  
  220.     }  
  221.       
  222.     return true;  
  223. }  
  224.   
  225. //在顶点集位置为v1和v2的顶点之间插入权值为weght的边(务必保持输入的准确性,否则.....)  
  226. template<class NameType, class DistType>   
  227. bool Graph<NameType, DistType>::InsertEdge(int v1, int v2, DistType weight)  
  228. {  
  229.     if (v1 < 0 && v1 > this->m_numVertexs && v2 < 0 && v2 > this->m_numVertexs)  
  230.     {  
  231.         cerr<<"边的位置参数错误,请检查! "<<endl;  
  232.         return false;  
  233.     }  
  234.     else  
  235.     {  
  236.         Edge<DistType> *pmove = m_pVertexTable[v1].padjEdge;  
  237.         if (pmove == NULL)//如果顶点v1没有邻边  
  238.         { //建立顶点v1的第一个邻边(该邻边指明了目的顶点)  
  239.             m_pVertexTable[v1].padjEdge = new Edge<DistType>(v2, weight);  
  240.             m_nnumEdges++;//图中边的数目  
  241.             return true;  
  242.         }else//如果有邻边  
  243.         {  
  244.             while (pmove->m_pnext)  
  245.             {  
  246.                 pmove = pmove->m_pnext;  
  247.             }  
  248.                 pmove->m_pnext = new Edge<DistType>(v2, weight);  
  249.                 m_nnumEdges++;//图中边的数目  
  250.                 return true;  
  251.         }  
  252.     }  
  253. }  
  254.   
  255.   
  256. template<class NameType, class DistType>  
  257. void Graph<NameType, DistType>::Dijkstra(int v, DistType *shPath)  
  258. {  
  259.     int num =GetNumVertexs();  
  260.     int *visited = new int[num];  
  261.     for (int i=0; i < num; i++)  
  262.     {//初始化  
  263.         visited[i] = 0;//未访问  
  264.         shPath[i] = this->GetWeight(v, i);//顶点v(当前中间点)到各个相邻顶点的边权值,其他情况返回无穷大  
  265.     }  
  266.   
  267.     visited[v] = 1;//第v个顶点初始化为被访问,并以他为中点点开始找最短路径  
  268.   
  269.     for (int i = 1; i < num; i++)  
  270.     {  
  271.         DistType min = this->m_Infinity;  
  272.         int u=0;  
  273.           
  274.         //寻找新的中间点u,依据就是数组中权值最小的那个点的位置(且没被访问过)  
  275.         for (int j=0; j < num; j++)  
  276.         {     
  277.             if (!visited[j])  
  278.             {  
  279.                 if (shPath[j]<min)  
  280.                 {  
  281.                     min = shPath[j];//获得当前shPath数组中的最小边权重  
  282.                     u = j;//用u来记录获取最小值时的顶点位置,即新的中间点  
  283.                 }  
  284.             }  
  285.         }  
  286.   
  287.         visited[u] = 1;//已经确定的最短路径  
  288.   
  289.         //以u为中间点寻找顶点v到顶点w的最短路径  
  290.         for (int w=0; w < num; w++)  
  291.         {    
  292.             DistType weight = this->GetWeight(u, w);//顶点u(当前中间点)到各个相邻顶点的边权值,其他情况返回无穷大  
  293.             if (!visited[w] && weight != this->m_Infinity )  
  294.             {  
  295.                 if ( shPath[u]+weight < shPath[w] )  
  296.                 {  
  297.                     shPath[w] = shPath[u] + weight;//更新顶点v到w的最短路径值  
  298.                 }  
  299.             }  
  300.         }  
  301.     }  
  302.     delete[] visited;  
  303. }  
  304.   
  305.   
  306.   
  307. //获得顶点v1的邻点v2后的邻点  
  308. template<class NameType, class DistType>   
  309. int Graph<NameType, DistType>::GetNext(int v1, int v2)  
  310. {  
  311.     if (-1 != v1)  
  312.     {  
  313.         Edge<DistType> *pmove = this->m_pVertexTable[v1].padjEdge;  
  314.         while (NULL != pmove->m_pnext)  
  315.         {  
  316.             if (pmove->m_nposTable==v2)  
  317.             {  
  318.                 return pmove->m_pnext->m_nposTable;  
  319.             }  
  320.             pmove = pmove->m_pnext;  
  321.         }          
  322.     }  
  323.     return -1;  
  324. }  
  325.   
  326. //从第v个顶点开始深度遍历  
  327. template<class NameType, class DistType>   
  328. void Graph<NameType, DistType>::DFS(int v, int *visited)  
  329. {  
  330.     cout << "->" << this->GetVertexName(v);  
  331.     visited[v] = 1;  
  332.     int firstVertex = this->GetFirst(v);//获得顶点v的第一个相邻顶点,若没有则返回-1  
  333.     while (-1 != firstVertex)  
  334.     {  
  335.         if (!visited[firstVertex])//如果没有访问过  
  336.         {  
  337.             cout << "->" << this->GetWeight(v, firstVertex);//获得顶点v及其邻点firstVertex之间的权值  
  338.             DFS(firstVertex, visited);  
  339.         }  
  340.         firstVertex = this->GetNext(v, firstVertex);//获得顶点v的邻点firstVertex后的邻点,如果没有就返回-1  
  341.     }  
  342. }  
  343.   
  344. template<class NameType, class DistType>   
  345. void Graph<NameType, DistType>::DFS()  
  346. {  
  347.     int *visited = new int[this->m_numVertexs];  
  348.     for (int i=0; i<this->m_numVertexs; i++)  
  349.     {  
  350.         visited[i] = 0;  
  351.     }  
  352.     cout << "head";  
  353.     DFS(0, visited);//从第一个顶点开始遍历  
  354.     cout << "--->end";  
  355. }  
  356.   
  357. template<class NameType, class DistType>   
  358. void Graph<NameType, DistType>::BFS()  
  359. {  
  360.     int *visited = new int[this->m_numVertexs];  
  361.     for (int i=0; i<this->m_numVertexs; i++)  
  362.     {  
  363.         visited[i] = 0;  
  364.     }  
  365.     cout << "head";  
  366.     BFS(0, visited);//从第一个顶点开始遍历  
  367.     cout << "--->end";  
  368. }  
  369.   
  370. //从第v个顶点开始广度遍历  
  371. template<class NameType, class DistType>   
  372. void Graph<NameType, DistType>::BFS(int v, int *visited)  
  373. {  
  374.     cout << "->" << this->GetVertexName(v);  
  375.     visited[v]=1;  
  376.     queue<int> que;//=new queue<int>[this->GetNumVertexs()];  
  377.     que.push(v);//进队(队列的末端)  
  378.     while (!que.empty())  
  379.     {  
  380.         v=que.front();//出队首元素  
  381.         que.pop();//删除队首元素  
  382.         int firstvertex=GetFirst(v);  
  383.         while(firstvertex != -1)  
  384.         {  
  385.             if (!visited[firstvertex])  
  386.             {  
  387.                 cout << "->" << this->GetWeight(v, firstvertex);//获得顶点v及其邻点firstVertex之间的权值  
  388.                 que.push(firstvertex);  
  389.                 visited[firstvertex]=1;  
  390.                 cout << "->" << this->GetVertexName(firstvertex);  
  391.             }  
  392.             firstvertex=GetNext(v,firstvertex);  
  393.         }  
  394.     }  
  395. }  
  396.   
  397. //获得在顶点集中的位置为v的顶点的名字  
  398. template<class NameType, class DistType>   
  399. NameType Graph<NameType, DistType>::GetVertexName(int v)  
  400. {  
  401.     if (v<0 || v>=this->m_numVertexs)  
  402.     {  
  403.         cerr << "查找的顶点位置参数有误,请检查!" <<endl;  
  404.         exit(1);  
  405.     }  
  406.     return m_pVertexTable[v].m_vertexName;  
  407.   
  408. }  
  409.   
  410. //获得顶点v的第一个相邻顶点,如果没有就返回-1  
  411. template<class NameType, class DistType>   
  412. int Graph<NameType, DistType>::GetFirst(int v)  
  413. {  
  414.     if (v<0 || v>=this->m_numVertexs)  
  415.     {  
  416.         return -1;  
  417.     }  
  418.     Edge<DistType> *ptemp = this->m_pVertexTable[v].padjEdge;  
  419.     return m_pVertexTable[v].padjEdge ? m_pVertexTable[v].padjEdge->m_nposTable : -1;  
  420. }  




2,主程序代码如下:

[html]  view plain  copy
 print ?
  1. // ConsoleAppMyGraph.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "Graph.h"  
  6. #include <iostream>  
  7. using namespace std;  
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.       
  11.     Graph<char *, int> graph(7);  
  12.     char *vertex[7] = {"【地大】", "【武大】", "【华科】", "【交大】", "【北大】", "【清华】", "【复旦】"};//顶点集  
  13.     for (int i=0; i<7; i++)  
  14.     {  
  15.         graph.InsertVertex(vertex[i]);  
  16.     }  
  17.     cout<<"一,图的初始化(邻结表存储):======================================"<<endl;  
  18.     graph.PrintGraph();  
  19.     cout<<"图中顶点的数目:"<<graph.GetNumVertexs()<<endl;  
  20.     cout <<endl;  
  21.   
  22.     int edge[][3] = {{0, 1, 43}/*地大到武大的距离*/, {0, 2, 12}, /*{1, 2, 38}*/ /*{2, 3 ,1325}*/   
  23.     /*{3, 6, 55}*/ {4, 5, 34}, /*{4, 6, 248}*/{0,3,400},{2,6,314},{2,4,37}};    //分配距离   
  24.     int len=sizeof(edge)/sizeof(edge[0]);  
  25.     for (int i=0; i < len; i++)  
  26.     {  
  27.         graph.InsertEdge(edge[i][0], edge[i][1], edge[i][2]);  
  28.         graph.InsertEdge(edge[i][1], edge[i][0], edge[i][2]);  
  29.     }  
  30.     cout<<"二,添加边后的图(无向图):=================================="<<endl;  
  31.     graph.PrintGraph();  
  32.     cout<<"图中边的数目(实际上是所示边数的两倍,因为是双向的):"<<graph.GetNumEdges()<<endl;  
  33.     cout <<endl;  
  34.   
  35.     cout<<"三,Dijkstra法最短路径为:=========================="<<endl;  
  36.     int shortestPath[7];//存储Dijkstra算法最短路径值  
  37.     graph.Dijkstra(0, shortestPath);  
  38.     for (int i=0; i<7; i++)  
  39.     {  
  40.         cout << graph.GetVertexValue(0) << "---><< graph.GetVertexValue(i)   
  41.             << ":   " << shortestPath[i] <<endl;  
  42.     }  
  43.     cout<<endl;  
  44.   
  45.     cout<<"四,图的遍历:=========================="<<endl;  
  46.     cout<<"1,DFS深度优先遍历结果:"<<endl;  
  47.     graph.DFS();  
  48.     cout<<endl<<endl;  
  49.     cout<<"2,BFS广度优先遍历结果:"<<endl;  
  50.     graph.BFS();  
  51.     cout<<endl<<endl;  
  52.   
  53.     system("color 0A");  
  54.     system("pause");  
  55.     return 0;  
  56. }  

3,测试结果如下:


参考资源

【1】《算法导论》

【2】《维基百科》

【3】http://www.cnblogs.com/rollenholt/archive/2012/04/09/2439055.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值