当前位置: 首页 > article >正文

【每日算法】Day 8-1:广度优先搜索(BFS)算法精讲——层序遍历与最短路径实战(C++实现)

掌握遍历与搜索的核心武器!今日深入解析广度优先搜索(BFS)的核心思想与实现技巧,结合树/图的层序遍历、最短路径等高频场景,彻底吃透队列在算法中的妙用。

一、BFS 核心思想

广度优先搜索(BFS) 是一种按层级展开的遍历算法,核心特性:

  1. 队列驱动:利用队列的先进先出特性管理遍历顺序

  2. 层级扩散:逐层访问节点,保证最短路径的首次命中

  3. 避免重复:通过标记机制防止重复访问节点

适用场景:

  • 树/图的层序遍历

  • 无权图的最短路径搜索

  • 状态空间的最小操作步数问题


二、算法模板与实现

通用 BFS 模板(C++)
void bfs(Node* start) {
    queue<Node*> q;
    unordered_set<Node*> visited; // 避免重复访问
    
    q.push(start);
    visited.insert(start);
    
    while (!q.empty()) {
        int levelSize = q.size(); // 当前层节点数
        for (int i = 0; i < levelSize; ++i) {
            Node* curr = q.front(); q.pop();
            // 处理当前节点
            for (Node* neighbor : curr->neighbors) {
                if (!visited.count(neighbor)) {
                    q.push(neighbor);
                    visited.insert(neighbor);
                }
            }
        }
    }
}

三、四大高频应用场景

场景1:二叉树的层序遍历(LeetCode 102)
vector<vector<int>> levelOrder(TreeNode* root) {
    vector<vector<int>> res;
    if (!root) return res;
    
    queue<TreeNode*> q;
    q.push(root);
    
    while (!q.empty()) {
        int n = q.size();
        vector<int> level;
        for (int i=0; i<n; ++i) {
            TreeNode* node = q.front(); q.pop();
            level.push_back(node->val);
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }
        res.push_back(level);
    }
    return res;
}
场景2:矩阵中的最短路径(LeetCode 1091)
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
    int n = grid.size();
    if (grid[0][0] || grid[n-1][n-1]) return -1;
    
    queue<pair<int, int>> q;
    q.push({0,0});
    grid[0][0] = 1; // 直接修改矩阵标记已访问
    
    int steps = 0;
    vector<vector<int>> dirs = {{-1,-1}, {-1,0}, {-1,1}, {0,-1}, 
                              {0,1}, {1,-1}, {1,0}, {1,1}};
    
    while (!q.empty()) {
        steps++;
        int size = q.size();
        while (size--) {
            auto [x,y] = q.front(); q.pop();
            if (x == n-1 && y == n-1) return steps;
            
            for (auto& d : dirs) {
                int nx = x + d[0], ny = y + d[1];
                if (nx>=0 && nx<n && ny>=0 && ny<n && grid[nx][ny]==0) {
                    grid[nx][ny] = 1;
                    q.push({nx, ny});
                }
            }
        }
    }
    return -1;
}
场景3:单词接龙(LeetCode 127)
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
    unordered_set<string> dict(wordList.begin(), wordList.end());
    if (!dict.count(endWord)) return 0;
    
    queue<string> q;
    q.push(beginWord);
    dict.erase(beginWord);
    int steps = 1;
    
    while (!q.empty()) {
        int n = q.size();
        while (n--) {
            string curr = q.front(); q.pop();
            if (curr == endWord) return steps;
            
            for (int i=0; i<curr.size(); ++i) {
                char orig = curr[i];
                for (char c='a'; c<='z'; ++c) {
                    curr[i] = c;
                    if (dict.count(curr)) {
                        q.push(curr);
                        dict.erase(curr);
                    }
                }
                curr[i] = orig;
            }
        }
        steps++;
    }
    return 0;
}
场景4:多源BFS(LeetCode 542)
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
    int m = mat.size(), n = mat[0].size();
    queue<pair<int, int>> q;
    
    // 初始化:所有0点入队
    for (int i=0; i<m; ++i) {
        for (int j=0; j<n; ++j) {
            if (mat[i][j] == 0) q.push({i,j});
            else mat[i][j] = -1; // 标记未访问
        }
    }
    
    vector<vector<int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};
    while (!q.empty()) {
        auto [x,y] = q.front(); q.pop();
        for (auto& d : dirs) {
            int nx = x + d[0], ny = y + d[1];
            if (nx>=0 && nx<m && ny>=0 && ny<n && mat[nx][ny]==-1) {
                mat[nx][ny] = mat[x][y] + 1;
                q.push({nx, ny});
            }
        }
    }
    return mat;
}

四、BFS 与 DFS 的对比

特性BFSDFS
数据结构队列
空间复杂度O(w)(w为最大宽度)O(h)(h为最大深度)
最短路径天然支持需完全遍历
实现方式迭代为主递归/迭代均可
适用场景层序遍历、最短路径拓扑排序、连通性检测

五、大厂真题实战

真题1:社交网络中的N度好友(某大厂2024面试)

题目描述:
给定用户的社交关系图,找出距离某用户恰好k层的好友
BFS解法:

vector<int> findKthFriends(int uid, int k, unordered_map<int, vector<int>> &graph) {
    queue<int> q;
    unordered_set<int> visited;
    q.push(uid);
    visited.insert(uid);
    int level = 0;
    
    while (!q.empty() && level < k) {
        level++;
        int size = q.size();
        while (size--) {
            int curr = q.front(); q.pop();
            for (int friend : graph[curr]) {
                if (!visited.count(friend)) {
                    visited.insert(friend);
                    q.push(friend);
                }
            }
        }
    }
    
    vector<int> res;
    if (level == k) {
        while (!q.empty()) {
            res.push_back(q.front());
            q.pop();
        }
    }
    return res;
}
真题2:迷宫最短路径(某大厂2023笔试)

题目描述:
给定包含障碍物的迷宫矩阵,求从起点到终点的最短步数
双向BFS优化:

int shortestPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& end) {
    unordered_set<string> head, tail, *phead, *ptail;
    head.insert(to_string(start[0])+","+to_string(start[1]));
    tail.insert(to_string(end[0])+","+to_string(end[1]));
    
    vector<vector<int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};
    int steps = 0;
    
    while (!head.empty() && !tail.empty()) {
        // 始终从较小集合扩展
        if (head.size() > tail.size()) {
            swap(head, tail);
            swap(phead, ptail);
        }
        
        unordered_set<string> tmp;
        for (auto pos : head) {
            // 解析坐标
            int x = stoi(pos.substr(0, pos.find(',')));
            int y = stoi(pos.substr(pos.find(',')+1));
            
            // 判断是否相遇
            if (tail.count(pos)) return steps;
            
            // 扩展节点
            for (auto& d : dirs) {
                int nx = x + d[0], ny = y + d[1];
                string key = to_string(nx)+","+to_string(ny);
                if (nx>=0 && nx<maze.size() && ny>=0 && ny<maze[0].size() 
                    && maze[nx][ny]==0 && !phead->count(key)) {
                    tmp.insert(key);
                }
            }
        }
        steps++;
        head = tmp;
    }
    return -1;
}

六、常见误区与优化技巧

  1. 队列溢出:未及时标记已访问节点导致重复入队

  2. 层级统计错误:未在每层开始时记录队列大小

  3. 空间浪费:使用额外存储标记访问状态(可直接修改输入矩阵)

  4. 性能优化

    • 双向BFS减少搜索空间

    • 优先队列优化带权图(Dijkstra)

    • 位压缩存储状态


LeetCode真题训练:

  • 200. 岛屿数量

  • 279. 完全平方数

  • 773. 滑动谜题


http://www.kler.cn/a/611385.html

相关文章:

  • 二十五、实战开发 uni-app x 项目(仿京东)- 前后端轮播图
  • 2025最新Chatbox全攻略:一键配置Claude/GPT/DeepSeek等主流模型(亲测可用)
  • # WebSocket 与 Socket.IO 对比与优化
  • RustDesk部署到linux(自建服务器)
  • How to use pgbench to test performance for PostgreSQL?
  • 完全背包模板
  • 突破反爬困境:SDK架构设计,为什么选择独立服务模式(四)
  • 本地部署 LangManus
  • K8S学习之基础五十一:k8s部署jenkins
  • 面试常问系列(二)-神经网络参数初始化之自注意力机制
  • 【hot100】刷题记录(52)-合并K个升序链表
  • How to share files with Linux mint 22 via samba in Windows
  • 【深度破解】爬虫反反爬核心技术实践:验证码识别与指纹伪装
  • 单表、多表查询练习
  • 一种电子发票数据的模糊查询方法
  • HTTP Header 中的 cookie 和 set-cookie
  • git 基本操作命令
  • 《深度剖析:鸿蒙系统不同终端设备的UI自适应布局策略》
  • Android第七次面试总结(Java和kotlin源码级区别 )
  • docker中yum出错解决方案