java dfs bfs 有向图_BFS和DFS分别用于有向图和无向图的一点心得和总结

本文详细介绍了有向图的BFS和DFS算法实现,通过邻接链表数据结构,讨论了在有向图中如何进行广度优先搜索和深度优先搜索。在BFS中,使用队列进行辅助,而DFS则使用栈,同时考虑了非强连通图的情况。文章还对比了无向图的BFS和DFS,强调了在无向图中设置三种状态的重要性,以避免重复访问节点的问题。最后,作者建议在学习算法时,结合纸笔进行思考以加深理解。
摘要由CSDN通过智能技术生成

图的数据结构为邻接链表adjacency list。

listVertex是一个储存Vertex* 顶点类指针的vector类型的STL;在Vertex类中有一个类成员nextEdgeNode,他是储存pair类型的vector容器;数对pair的first表示边指向的顶点序号,second表示边的序号。

四个函数都只有一个参数,在声明时提供了默认的参数值-1;参数表示起始顶点的编号

先放一个测试用的图、有向图的邻接链表、无向图的邻接链表。

ab4421749fc06e4dd9fcea5ddf5965b2.png

175a466d48e7d17b4edbb9c4eac25048.png

769a309089b5bd4a84261e8b7331393d.png

以下是有向图的BFS

1 void Graph::BFSListO(intstartFrom) {2 /*the principle is to firstly choose a random vertex, if it has 0 out degree, then choose the first3 unvisited vertex in the list; moreover,if one way is exhausted to continue,also push the first univisited vertex4 in the list to the queue*/

5 cout << "BFS of oriented Adjacey List:" <

9 while (listVertex[rdm]->nextEdgeNode.empty()) {10 rdm = rand() % sze;//randomly choose a vertex whose out degree is not 0

11 }12 queuemyQueue;13 if(startFrom==-1)//default treatment is random choose

14 myQueue.push(listVertex[rdm]);15 else {//designated choose

16 myQueue.push(listVertex[startFrom-1]);17 }18 while (!myQueue.empty()) {//travel through until there is nothing in the queue

19 Vertex* V =myQueue.front();20 if (V->color == 0) {21 V->color = 1; //O black(unvisited) & 1 white(visited)//V visited white 1

22 cout << "Vertex visit

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值