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.pswp.cn/news/379409.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/379409.shtml
英文地址,請注明出處:http://en.pswp.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.掌握查詢語句中的通配符的使用。 …