BFS

BFS广度优先搜索:一般借助队列实现具体问题求解,跟深度优先搜索相似,也是一种枚举;

题目大意:

详见我的博客DFS

基本思路:

用队列实现BFS;

代码如下:

(这次就不输出路径了,不过我留着用f表示在队列中的位置,读者可以试着写一写输出最短路径的情况,题目是《啊哈!算法》上的,所以代码大致相似,因为我就是这么学的)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>


using namespace std;


const int maxn = 2500+10;
const int maxv = 100+10;
struct note
{
    int x,y;
    int f;
    int s;
};
note que[maxn];
int arr[maxv][maxv],book[maxv][maxv];
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int r,c,flag;
int main()
{
    scanf("%d%d",&r,&c);
    for(int i=1;i<=r;++i)
        for(int j=1;j<=c;++j)
            scanf("%d",&arr[i][j]);
    int startx,starty,endx,endy;
    scanf("%d%d%d%d",&startx,&starty,&endx,&endy);
    int head=1,tail=1;
    que[tail].x=startx;
    que[tail].y=starty;
    que[tail].f=0;
    que[tail].s=0;
    tail++;
    book[startx][starty]=1;
    while(head<tail)
    {
        int tx,ty;
        for(int i=0;i<=3;++i)
        {
            tx=que[head].x+next[i][0];
            ty=que[head].y+next[i][1];
            if(tx<1||tx>r||ty<1||ty>c) continue;
            if(arr[tx][ty]==0&&book[tx][ty]==0)
            {
                book[tx][ty]=1;
                que[tail].x=tx;
                que[tail].y=ty;
                que[tail].s=que[head].s+1;
                que[tail].f=head;
                tail++;
            }
            if(tx==endx&&ty==endy)
            {
                flag=1;
                break;
            }
        }
        if(flag==1) break;
        head++;
    }
    printf("%d",que[tail-1].s);
    return 0;
}

测试样例:

5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3

样例输出:

7

### 广度优先搜索(BFS算法实现 广度优先搜索(BFS)是一种用于遍历或搜索树或图的算法。它按照层次顺序访问节,通常从根节开始,逐层向下扩展到叶子节[^3]。 以下是基于队列的数据结构来实现 BFS 的标准方法: #### 使用伪代码描述 BFS 实现 ```plaintext function BFS(graph, start_vertex): create an empty queue Q enqueue(start_vertex) into Q mark start_vertex as visited while Q is not empty: current_vertex = dequeue(Q) visit(current_vertex) for each neighbor of current_vertex in graph.adjacentEdges(current_vertex): if neighbor is not visited: mark neighbor as visited enqueue(neighbor) into Q ``` #### 基于 Python 的 BFS 实现 下面是一个完整的 Python 实现示例,适用于无向图或有向图中的 BFS 遍历: ```python from collections import deque def bfs(graph, start_node): """ Perform Breadth-First Search (BFS) on a given graph. :param graph: Dictionary representing adjacency list of the graph :param start_node: Starting node for BFS traversal :return: List containing nodes visited during BFS traversal """ visited = set() # Set to keep track of visited nodes result = [] # List to store the order of visited nodes queue = deque([start_node]) # Initialize queue with the start node visited.add(start_node) # Mark the start node as visited while queue: current_node = queue.popleft() result.append(current_node) # Add current node to the result list # Explore neighbors of the current node for neighbor in graph.get(current_node, []): if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) return result # Example usage if __name__ == "__main__": # Define a sample graph using an adjacency dictionary graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } start_node = 'A' traversal_order = bfs(graph, start_node) print(f"BFS Traversal Order: {traversal_order}") ``` 此代码实现了 BFS 算法的核心逻辑,并通过 `deque` 数据结构模拟了一个先进先出(FIFO)队列的行为。对于给定的输入图,该函数返回按 BFS 访问顺序排列的节列表[^4]。 #### 关键特性说明 1. **时间复杂度**: 如果图中有 \(V\) 个顶和 \(E\) 条边,则 BFS 的时间复杂度为 \(O(V + E)\)[^1]。 2. **空间复杂度**: 主要由队列占用的空间决定,在最坏情况下可能达到 \(O(V)\),即当所有顶都在同一层时[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值