【搜索】【广搜模板】

ACM模板

C++queue的应用


struct note{  
    int x; //横坐标 
    int step;  //步数 
    int y;  //纵坐标 
};  

void BFS(note front_head)//BFS   
{  
    queue<note>Q;//建立空队列   
    Q.push(front_head);//将起始点加入队列   

    note next_queue;//下一个队列元素   
    note now_head;//当前队头元素   
    while(!Q.empty())//循环条件是队列不为空   
    {  
        now_head = Q.front();//找到当前队头元素   
        Q.pop();//已经找到则出队   
        for(i = 0; i < 8; i ++)//搜索8个方向   
        {  
            next_queue.x = now_head.x + NEXT[i][0];  
            next_queue.y = now_head.y + NEXT[i][1];  
            if(next_queue.x < 0||next_queue.y <0||next_queue.x > 7||next_queue.y > 7)  
                continue;  

            if(book[next_queue.x ][next_queue.y ]!= 1)//没有走过该点   
            {  
                book[next_queue.x ][next_queue.y ] = 1;  
                next_queue.step = now_queue.step+1;  

                Q.push(next_queue);//将找到满足条件的下一个队列元素加入队尾   
                //如果下一个队列元素满足终止条件,结束函数   
                if(next_queue.x == end_i&&next_queue.y == end_j)  
                {  
                    step = next_queue.step;  
                    return;  
                }
            }  
        }  
    }   
    return;  
}  
### 广 (BFS) 算法模板与实现 广(BFS)是一种基于图的搜索算法,通常采用队列来实现逐层扩展节点的过程。以下是几种常见的 BFS 模板及其应用场景。 #### 图结构下的 BFS 实现 对于图结构,可以使用邻接表表示图,并通过队列完成 BFS 遍历过程。以下是一个 Python 的实现示例: ```python from collections import deque, defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) def bfs(self, start_node): visited = set() queue = deque([start_node]) result = [] while queue: node = queue.popleft() # 取出队首元素 if node not in visited: # 如果未访问过,则标记为已访问 visited.add(node) result.append(node) for neighbor in self.graph[node]: if neighbor not in visited: queue.append(neighbor) # 将邻居节点加入队列 return result ``` 上述代码展示了如何构建一个简单的无向图并通过 BFS 进行遍历[^2]。 --- #### 树结构下的 BFS 层次遍历 在二叉树场景下,可以通过队列实现层次遍历(即按层输出节点值)。下面提供了一个 C++ 和 Python 版本的例子: ##### **C++ 实现** ```cpp #include <vector> #include <queue> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if (!root) return res; // 若根节点为空,直接返回空结果 queue<TreeNode*> q; q.push(root); while (!q.empty()) { int size = q.size(); vector<int> currentLevel; for (int i = 0; i < size; ++i) { // 处理当前层的所有节点 TreeNode* node = q.front(); q.pop(); currentLevel.push_back(node->val); // 记录当前节点值 if (node->left) q.push(node->left); // 左子节点入队 if (node->right) q.push(node->right); // 右子节点入队 } res.push_back(currentLevel); // 当前层的结果存入最终结果集 } return res; } ``` ##### **Python 实现** ```python from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def level_order_traversal(root): if not root: return [] result = [] queue = deque([root]) while queue: level_size = len(queue) current_level = [] for _ in range(level_size): # 遍历当前层的所有节点 node = queue.popleft() current_level.append(node.val) if node.left: queue.append(node.left) # 左子节点入队 if node.right: queue.append(node.right) # 右子节点入队 result.append(current_level) # 存储当前层的结果 return result ``` 此部分实现了针对二叉树的层序遍历功能[^4]。 --- #### 表格类型的 BFS 应用 当面对网格或矩阵问题时,BFS 常被用来解决最短路径等问题。例如在一个二维数组中寻找从起点到终点的最短距离。 ```python from collections import deque def shortest_path(grid, start, end): rows, cols = len(grid), len(grid[0]) directions = [(0, 1), (1, 0), (-1, 0), (0, -1)] # 上下左右四个方向移动 queue = deque([(start, 0)]) # 起点坐标以及步数初始化 visited = set([start]) # 使用集合记录已经访问过的点 while queue: (x, y), steps = queue.popleft() if (x, y) == end: # 找到目标点 return steps for dx, dy in directions: # 枚举四个方向 nx, ny = x + dx, y + dy if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] != '#' and (nx, ny) not in visited: visited.add((nx, ny)) queue.append(((nx, ny), steps + 1)) # 下一状态入队 return -1 # 如果无法到达终点,返回 -1 ``` 这段代码适用于迷宫类问题中的最短路径求解[^1]。 --- ### 总结 广(BFS)的核心在于利用队列逐步探索每一层相邻节点,适合于解决诸如连通性检测、最短路径计算等经典问题。不同数据结构(如图、树、表格)都可以灵活应用 BFS 来解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值