博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++实现图的搜索(DFS和BFS)
阅读量:7050 次
发布时间:2019-06-28

本文共 2104 字,大约阅读时间需要 7 分钟。

1 #include
2 #include
3 4 #include
5 #define Max 20 6 using namespace std; 7 8 class Vertex 9 { 10 public: 11 Vertex(char lab) 12 { 13 Label=lab; 14 wasVisited=false; 15 } 16 public: 17 bool wasVisited; 18 char Label; 19 }; 20 21 22 class Graph 23 { 24 25 public: 26 Graph();//构造函数 27 ~Graph();//析构函数 28 void addVertex(char lab);//增加一个节点 29 void addEdge(int start,int end);//增加一条边,起点到终点 30 void printMatrix();//打印出矩阵 31 void showVertex(int v); 32 void DFS(); 33 void BFS(); 34 private: 35 Vertex* vertexList[Max]; //存放每个节点的指针的数组 36 int nVerts;//实际数量 37 int adjMat[Max][Max];//矩阵 38 int getAdjUnvisitedVertex(int v);//获得其相邻的节点 在邻接矩阵里找其最近的 39 }; 40 41 void Graph::DFS() 42 { 43 stack
gStack; 44 vertexList[0]->wasVisited=true; 45 showVertex(0); 46 gStack.push(0); 47 int v; 48 while(gStack.size()>0) 49 { 50 v=getAdjUnvisitedVertex(gStack.top()); 51 if(v==-1) 52 { 53 cout<<"出:"<
<
wasVisited=true; 59 showVertex(v); 60 gStack.push(v); 61 } 62 63 } 64 65 for(int j=0;j
wasVisited=false; 67 68 69 } 70 void Graph::BFS() 71 { 72 queue
gQueue; 73 vertexList[0]->wasVisited=true; 74 showVertex(0); 75 gQueue.push(0); 76 int vert1,vert2; 77 while(gQueue.size()>0) 78 { 79 vert1=gQueue.front(); 80 gQueue.pop(); 81 vert2=getAdjUnvisitedVertex(vert1); 82 while(vert2!=-1) 83 { 84 vertexList[vert2]->wasVisited=true; 85 showVertex(vert2); 86 gQueue.push(vert2); 87 vert2=getAdjUnvisitedVertex(vert1); 88 } 89 } 90 cout<
wasVisited=false; 93 94 95 } 96 97 int Graph::getAdjUnvisitedVertex(int v)//得到其相邻节点 98 { 99 for(int j=0;j
wasVisited==false))//找其第一个相邻(邻接)的且没有被访问过的102 return j;103 }104 105 return -1;106 107 }108 void Graph::showVertex(int v) //展示该下标对应的节点109 {110 cout<
Label<<" ";111 }112 Graph::Graph()113 {114 115 nVerts=0;116 for(int i=0;i

 

转载于:https://www.cnblogs.com/libin123/p/10420216.html

你可能感兴趣的文章
六、python小功能记录——递归删除bin和obj内文件
查看>>
阅读《移山之道》及讲义感想
查看>>
python进阶-面向对象编程五:类的内置方法
查看>>
JAVA入门到精通-第52讲-面试题讲评
查看>>
05-spark streaming & kafka
查看>>
python杂记
查看>>
cd 简化命令
查看>>
LeetCode--205--同构字符串
查看>>
python-ConfigParser模块【读写配置文件】
查看>>
wireshark使用方法总结
查看>>
Window Server 2008 R2 TFS2010 安装前的准备
查看>>
20141123
查看>>
translucent 属性
查看>>
android listView嵌套gridview的使用心得
查看>>
[ES7] Descorator: evaluated & call order
查看>>
安卓动态调试七种武器之离别钩 – Hooking(上)
查看>>
从P6 EPPM 8 R3 到P6 EPPM 16 R1 有哪些改变?
查看>>
Android Studio2.0 教程从入门到精通Windows版 - 安装篇
查看>>
Linux 系统磁盘满处理方法
查看>>
Java HashMap Demo
查看>>