【代码随想录】广度优先搜索

思路分析

image
先前已经做过一道深度优先搜索了,可以看出,DFS比较适合求两点之间的所有路径这样的问题,因为其路径都是逐条求出的,而BFS则可能一下子求出多条路径,适合用来求最短路径。
关于BFS的过程前面已经学习过很多次了,遍历到一个节点时要先保存其所有邻接节点再继续向下遍历,一般是使用一个队列来完成。
image

代码模版

int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 表示四个方向
// grid 是地图,也就是一个二维数组
// visited标记访问过的节点,不要重复访问
// x,y 表示开始搜索节点的下标
void bfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y) {
    queue<pair<int, int>> que; // 定义队列
    que.push({x, y}); // 起始节点加入队列
    visited[x][y] = true; // 只要加入队列,立刻标记为访问过的节点
    while(!que.empty()) { // 开始遍历队列里的元素
        pair<int ,int> cur = que.front(); que.pop(); // 从队列取元素
        int curx = cur.first;
        int cury = cur.second; // 当前节点坐标
        for (int i = 0; i < 4; i++) { // 开始想当前节点的四个方向左右上下去遍历
            int nextx = curx + dir[i][0];
            int nexty = cury + dir[i][1]; // 获取周边四个方向的坐标
            if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;  // 坐标越界了,直接跳过
            if (!visited[nextx][nexty]) { // 如果节点没被访问过
                que.push({nextx, nexty});  // 队列添加该节点为下一轮要遍历的节点
                visited[nextx][nexty] = true; // 只要加入队列立刻标记,避免重复访问
            }
        }
    }

}

补充:pair,在这里用来表示点的坐标

image
https://blog.csdn.net/sevenjoin/article/details/81937695

posted @ 2024-03-20 16:55  SaTsuki26681534  阅读(2)  评论(0编辑  收藏  举报