当前位置:   article > 正文

【数据结构】邻接矩阵之深度优先遍历DFS_根据邻接矩阵写出深度优先遍历

根据邻接矩阵写出深度优先遍历

以某一顶点为起点,深度遍历,v->w1->w2->.......u

回退一步,看是否有其他未被访问的邻接点 

  1. #include<iostream>
  2. using namespace std;
  3. #define MaxInt 32767 //表示极大值
  4. #define MVNum 100 //最大顶点数
  5. typedef char VerTexType; //设置顶点类型为字符型
  6. typedef int ArcType; //设置权重为整型
  7. typedef struct{
  8. VerTexType vexs[MVNum]; //顶点表
  9. ArcType arcs[MVNum][MVNum]; //邻接矩阵
  10. int vexnum,arcnum; //顶点数和边数
  11. }AMGraph;
  12. 从顶点表中查找顶点
  13. int LocateVex(AMGraph G,VerTexType u){
  14. int i;
  15. for(i=0;i<G.vexnum;i++)
  16. if(u==G.vexs[i]) return i;
  17. return -1;
  18. }
  19. //构造无向图
  20. int CreateUDG(AMGraph &G){
  21. int i,j,k;
  22. cout<<"请输入顶点数和边数:";
  23. cin>>G.vexnum>>G.arcnum;
  24. cout<<"输入顶点:";
  25. for(i=0;i<G.vexnum;i++) cin>>G.vexs[i];
  26. for(i=0;i<G.vexnum;i++)
  27. for(j=0;j<G.vexnum;j++)
  28. G.arcs[i][j]=0;
  29. for(k=0;k<G.arcnum;k++){
  30. VerTexType v1,v2;
  31. ArcType w;
  32. cout<<"输入依附的顶点:";
  33. cin>>v1>>v2;
  34. i=LocateVex(G,v1);
  35. j=LocateVex(G,v2);
  36. G.arcs[i][j]=1;
  37. G.arcs[j][i]=G.arcs[i][j];
  38. }
  39. return 1;
  40. }
  41. //输出邻接矩阵
  42. void Show(AMGraph G){
  43. int i,j;
  44. for(i=0;i<G.vexnum;i++){
  45. for(j=0;j<G.vexnum;j++)
  46. if(G.arcs[i][j]==MaxInt) cout<<"∞"<<' ';
  47. else cout<<G.arcs[i][j]<<' ';
  48. cout<<endl;
  49. }
  50. }
  51. bool visited[MVNum]; //辅助数组,标记该结点是否被访问
  52. //深度优先遍历DFS
  53. void DFS(AMGraph G,int v){
  54. int w;
  55. cout<<G.vexs[v]; visited[v]=1; //访问第v个结点
  56. for(w=0;w<G.vexnum;w++) //依次检查v所在行
  57. if(G.arcs[v][w] && !visited[w]) //如果w是邻接点且未被访问,则递归调用DFS
  58. DFS(G,w);
  59. }
  60. int main(){
  61. AMGraph G;
  62. CreateUDG(G);
  63. cout<<endl<<"构造的无向图为:"<<endl;
  64. Show(G);
  65. int v;
  66. cout<<endl<<"请输入DFS起点:";
  67. cin>>v;
  68. cout<<"深度优先遍历DFS结果为:";
  69. DFS(G,v);
  70. return 1;
  71. }

运行结果: 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/596649
推荐阅读
相关标签
  

闽ICP备14008679号