bfs广度优先搜索算法_图的广度优先搜索(BFS)

bfs广度优先搜索算法

What you will learn?

您将学到什么?

How to implement Breath first search of a graph?

如何实现图的呼吸优先搜索?

Breadth First Search is a level-wise vertex traversal process. Like a tree all the graphs have vertex but graphs have cycle so in searching to avoid the coming of the same vertex we prefer BFS

Algorithm:

To implement the BFS we use queue and array data structure.

There are two cases in the algorithm:

  1. Whenever we visit a vertex we mark it visited and push its adjacent non-visited vertices into the queue and pop the current vertex from the queue.

  2. If all the adjacent vertices are visited then only pop the current vertex from the queue.

Consider this graph,

BFS Graph Example 1

According to our algorithm, the traversal continues like,

Hence all the vertices are visited then only pop operation is performed and queue will be empty finally.


C++ Implementation:

#include <bits/stdc++.h>
using namespace std;
//	Make a pair between vertex x and vertex y 
void addedge(list<int> *ls,int x,int y){
ls[x].push_back(y);
ls[y].push_back(x);
return;
} 
//Breath First Search of a Graph
void BFS(list<int>*ls,int num,int x){
bool *visit= new bool[num];
for(int i=0;i<num;i++){
visit[i]=false;
}
queue<int> q;
q.push(x);
while(!q.empty()){
int s=q.front();
q.pop();
if(!visit[s]){
visit[s]=true;
cout<<s<<" ";
list<int>::iterator it;
for(it=ls[s].begin();it!=ls[s].end();it++){
q.push(*it);
}
}
}
}
// Print the Adjacency List
void print(list<int> *ls,int num){
list<int>::iterator it;
for(int i=0;i<6;i++){
cout<<i<<"-->";
for(it=ls[i].begin();it!=ls[i].end();it++){
cout<<*it<<"-->";
}
cout<<endl;
}
}
int main(){
int num=6;
cout<<"Enter the no. of vertices : 6\n";
list<int> *ls=new list<int>[num];
addedge(ls,0,2);
addedge(ls,2,3);
addedge(ls,3,4);
addedge(ls,4,5);
addedge(ls,2,5);
addedge(ls,1,4);
addedge(ls,3,0);
cout<<"Print of adjacency list:"<<endl;
print(ls,6);
cout<<"BFS"<<endl;
BFS(ls,6,0);
return 0;
}

Output



TOP Interview Coding Problems/Challenges

  • Run-length encoding (find/print frequency of letters in a string)

  • Sort an array of 0's, 1's and 2's in linear time complexity

  • Checking Anagrams (check whether two string is anagrams or not)

  • Relative sorting algorithm

  • Finding subarray with given sum

  • Find the level in a binary tree with given sum K

  • Check whether a Binary Tree is BST (Binary Search Tree) or not

  • 1[0]1 Pattern Count

  • Capitalize first and last letter of each word in a line

  • Print vertical sum of a binary tree

  • Print Boundary Sum of a Binary Tree

  • Reverse a single linked list

  • Greedy Strategy to solve major algorithm problems

  • Job sequencing problem

  • Root to leaf Path Sum

  • Exit Point in a Matrix

  • Find length of loop in a linked list

  • Toppers of Class

  • Print All Nodes that don't have Sibling

  • Transform to Sum Tree

  • Shortest Source to Destination Path



Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.


广度优先搜索是一个逐层的顶点遍历过程。 像一棵树一样,所有图都具有顶点,但是图却具有循环,因此为了避免出现相同的顶点,我们选择了BFS

算法:

为了实现BFS,我们使用队列和数组数据结构。

该算法有两种情况:

  1. 每当我们访问顶点时,都会将其标记为已访问,并将其相邻的未访问顶点推入队列,然后从队列中弹出当前顶点。

  2. 如果访问了所有相邻的顶点,则仅从队列中弹出当前顶点。

考虑一下这张图,

BFS图示例1

根据我们的算法,遍历继续像

因此,所有顶点都将被访问,然后仅执行弹出操作,并且队列最终将为空。


C ++实现:

 # include  < bits/stdc++.h >
using namespace std ;
//	Make a pair between vertex x and vertex y 
void addedge ( list < int > * ls , int x , int y ) {
ls [ x ] . push_back ( y ) ;
ls [ y ] . push_back ( x ) ;
return ;
} 
//Breath First Search of a Graph
void BFS ( list < int > * ls , int num , int x ) {
bool * visit = new bool [ num ] ;
for ( int i = 0 ; i < num ; i + + ) {
visit [ i ] = false ;
}
queue < int > q ;
q . push ( x ) ;
while ( ! q . empty ( ) ) {
int s = q . front ( ) ;
q . pop ( ) ;
if ( ! visit [ s ] ) {
visit [ s ] = true ;
cout < < s < < "   " ;
list < int > :: iterator it ;
for ( it = ls [ s ] . begin ( ) ; it ! = ls [ s ] . end ( ) ; it + + ) {
q . push ( * it ) ;
}
}
}
}
// Print the Adjacency List
void print ( list < int > * ls , int num ) {
list < int > :: iterator it ;
for ( int i = 0 ; i < 6 ; i + + ) {
cout < < i < < " --> " ;
for ( it = ls [ i ] . begin ( ) ; it ! = ls [ i ] . end ( ) ; it + + ) {
cout < < * it < < " --> " ;
}
cout < < endl ;
}
}
int main ( ) {
int num = 6 ;
cout < < " Enter the no. of vertices : 6 \n " ;
list < int > * ls = new list < int > [ num ] ;
addedge ( ls , 0 , 2 ) ;
addedge ( ls , 2 , 3 ) ;
addedge ( ls , 3 , 4 ) ;
addedge ( ls , 4 , 5 ) ;
addedge ( ls , 2 , 5 ) ;
addedge ( ls , 1 , 4 ) ;
addedge ( ls , 3 , 0 ) ;
cout < < " Print of adjacency list: " < < endl ;
print ( ls , 6 ) ;
cout < < " BFS " < < endl ;
BFS ( ls , 6 , 0 ) ;
return 0 ;
}

输出量



最佳面试编码问题/挑战

  • 游程编码(字符串中字母的查找/打印频率)

  • 以线性时间复杂度对0、1和2的数组进行排序

  • 检查字谜(检查两个字符串是否是字谜)

  • 相对排序算法

  • 查找给定总和的子数组

  • 在给定总和K的二叉树中找到级别

  • 检查二叉树是否为BST(二叉搜索树)

  • 1 [0] 1个样式计数

  • 大写一行中每个单词的第一个和最后一个字母

  • 打印二叉树的垂直和

  • 打印二叉树的边界和

  • 反转单个链表

  • 解决主要算法问题的贪婪策略

  • 工作排序问题

  • 根到叶的路径总和

  • 矩阵中的出口点

  • 在链表中查找循环长度

  • 一流的礼帽

  • 打印所有没有兄弟的节点

  • 转换为求和树

  • 最短的源到目标路径



评论和讨论

广告:您是博主吗? 加入我们的Blogging论坛 。


翻译自: https://www.includehelp.com/data-structure-tutorial/breadth-first-search-bfs-of-a-graph.aspx

bfs广度优先搜索算法

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/379409.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

考研C++必刷题(一)

【程序1】 题目&#xff1a;有1、2、3、4个数字&#xff0c;能组成多少个互不相同且无重复数字的三位数&#xff1f;都是多少&#xff1f; 解题思路&#xff1a; 利用三层循环&#xff0c;分别控制百位十位个位&#xff0c;若百位十位个位有重复的&#xff0c;则不输出即可。 代…

关于计算机存储单位?

关于计算机存储单位&#xff1f; 计算机只能识别二进制。(1010100110. . . ) 1字节 8bit&#xff08;8比特&#xff09;–>1byte 8bit 1bit 就是一个 1 或 0 1KB 1024byte byte是[-128 ~ 127]&#xff0c;共可以标识256个不同的数字。 byte类型的最大值是怎么计算出来的…

ffmpeg 命令转封装

1&#xff1a; 改变编码格式 原mp4文件:视频是h264 音频是aac 视频转成h265&#xff0c;音频转成mp3&#xff08;容器为mkv&#xff0c;有些容器不一定支持放h265的&#xff09; ffmpeg -i test_60s.mp4 -vcodec libx265 -acodec libmp3lame out_h265_mp3.mkv 播放&#xff1a…

Delphi 2010 DataSnap封装COM对象

在Delphi 2010中,DataSnap已完全可以不使用COM了.想起在windows上配置COM,就麻烦的很,如果在本机还好说,在远程要涉及到权限等诸多问题(用SocketConnection要方便一些). 如果早期写的程序中有许多COM对象,我们可以通过DataSnap的封装,使用适配器模式简单地封装一下,那么在客户端…

JavaScript中带有示例的Math.PI属性

JavaScript | Math.PI属性 (JavaScript | Math.PI Property) Math.PI is a property in math library of JavaScript that is used to find the value of PI(π) which is a mathematical constant whose value is 3.141. It is generally used to solve problems related to c…

设计模式笔记——Bridge

桥接模式Bridge Pattern 组合关系&#xff08;实心菱形&#xff09;&#xff1a;强的拥有关系&#xff0c;体现了严格的整体和部分的关系&#xff0c;部分和整体的生命周期相同。 聚合关系&#xff08;空心菱形&#xff09;&#xff1a;弱的拥有关系&#xff0c;A对象可以包含B…

实验7 视图操作

实验7 视图操作一、实验目的 1.了解视图的功能。 2.掌握创建和查看视图的方法。 3.掌握视图修改和删除视图的方法。 二、实验要求 创建student数据库中的相关视图。 三、实验步骤 1.在members表中创建地址为“湖南株洲”的会员的视图V_addr&#xff0c;SQL代码如下所示&#x…

从日志服务器接收的对 metaWeblog.newPost 方法的响应无效的解决方案

今天用windows Live Writer(WLW)写博客出现了“从日志服务器接收的对 metaWeblog.newPost 方法的响应无效”的故障。之前用的还好好的。于是我祭起google大法。从网上搜索了不少资料都是关于WP&#xff0c;没有关于z-blog。这些文章提到可能的问题是诸如插件冲突、utf编码之类的…

汇编语言-006(数组操作 、字符串应用、PUSHFD_POPFD 、PUSHAD_POPAD 、 子程序 函数、 USES 、 INC_DEC )

1: 计算斐波那契数列前7个数值之和 .386 .model flat,stdcall.stack 4096 ExitProcess PROTO,dwExitCode:DWORD.data.code main PROCmov esi,1mov edi,1mov eax,2mov ecx,5 L1: mov ebx,esiadd ebx,edimov esi,edimov edi,ebxadd eax,ebxloop L1INVOKE ExitProcess,0 main END…

弗林的计算机体系结构分类

计算机体系结构分类 (Classification of computer architecture) According to Flynns there are four different classification of computer architecture, 根据弗林的说法&#xff0c;计算机体系结构有四种不同的分类&#xff0c; 1)SISD(单指令单数据流) (1) SISD (Single…

读入txt

用C#读取txt文件的方法1、使用FileStream读写文件 文件头&#xff1a; using System;using System.Collections.Generic;using System.Text;using System.IO; 读文件核心代码&#xff1a; byte[] byData new byte[100];char[] charData new char[1000]; try{FileStream sFile…

实验6 数据查询--高级查询

实验6 数据查询--高级查询一、实验目的 1.掌握查询结果排序的方法。 2.掌握排序结果进行计算的方法。 3.掌握排序结果分组的方法。 4.掌握排序结果分组后再选择的方法。 二、实验要求 应用SELECT语句对数据库eshop中数据进行指定条件的高级查询。 三、实验步骤 1.查询性别为“…

Python程序可打印今天的年,月和日

In the below example – we are implementing a python program to print the current/ todays year, month and year. 在下面的示例中-我们正在实现一个python程序来打印当前/今天的年&#xff0c;月和年 。 Steps: 脚步&#xff1a; Import the date class from datetime …

工资年结时提示“上年数据已经结转”

解决方案&#xff1a;执行如下SQL语句即可解决&#xff1a;use ufsystem update ua_account_sub set bclosing0 where cacc_id001 and iyear2005 and csub_idwa 重新年结即可 问题分析&#xff1a;产生问题的原因是用户进行过工资的年结&#xff0c;在业务数据需要调整&…

汇编语言-007(ADD_SUB_NEG 、 PUSH和POP指令应用 、 AND,OR,XOR使用 、 条件跳转应用)

1&#xff1a; ADD_SUB_NEG : ADD伪指令增加数值&#xff0c;SUB伪指令减少数值,NEG取反1 .386 .model flat,stdcall.stack 4096 ExitProcess PROTO,dwExitCode:DWORD.data var1 DWORD 10000h var2 DWORD 20000h.code main PROCmov eax,var1add eax,var2mov eax,var2sub eax,v…

Automatic Reference Counting

Automatic Reference Counting http://clang.llvm.org/docs/AutomaticReferenceCounting.html转载于:https://www.cnblogs.com/StarMud/articles/2642263.html

实验5 数据查询--连接查询

实验5 数据查询--连接查询一、实验目的 1.熟悉等值联接查询的方法。 2.熟悉非等值联接查询的方法。 3.熟悉自身联接查询的方法。 4.熟悉外联接查询的方法。 5.熟悉复合条件联接的方法。 二、实验要求 应用SELECT语句对数据库eshop中数据进行指定条件的连接查询。 三、实验步骤…

Java RandomAccessFile readInt()方法与示例

RandomAccessFile类readInt()方法 (RandomAccessFile Class readInt() method) readInt() method is available in java.io package. readInt()方法在java.io包中可用。 readInt() method is used to read signed 32-bit integer value from this RandomAccessFile. readInt()方…

天高地厚(转)

信乐团-天高地厚作词:武雄作曲:詹凌驾 keith stuart你累了没有可否伸出双手想拥抱怎能握着拳头我们还有很多梦没做还有很多明天要走要让世界听见我们的歌准备好没有时间不再回头想要飞不必任何理由不管世界尽头多寂寞你的身边一定有我我们说过不管天高地厚想飞到那最高最远最洒…

实验4 数据查询--简单查询

实验4 数据查询--简单查询一、实验目的 1.掌握SELECT语句的基本方法。 2.掌握从表中查询特定行的方法。 3.掌握从表中查询前N行的方法。 4.掌握从查询结果中去掉重复行的方法。 5.掌握使用列的别名的方法。 6.掌握从表中查询特定列的方法。 7.掌握查询语句中的通配符的使用。 …