【每日算法】Day 8-1:广度优先搜索(BFS)算法精讲——层序遍历与最短路径实战(C++实现)
掌握遍历与搜索的核心武器!今日深入解析广度优先搜索(BFS)的核心思想与实现技巧,结合树/图的层序遍历、最短路径等高频场景,彻底吃透队列在算法中的妙用。
一、BFS 核心思想
广度优先搜索(BFS) 是一种按层级展开的遍历算法,核心特性:
队列驱动:利用队列的先进先出特性管理遍历顺序
层级扩散:逐层访问节点,保证最短路径的首次命中
避免重复:通过标记机制防止重复访问节点
适用场景:
-
树/图的层序遍历
-
无权图的最短路径搜索
-
状态空间的最小操作步数问题
二、算法模板与实现
通用 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 的对比
特性 | BFS | DFS |
---|---|---|
数据结构 | 队列 | 栈 |
空间复杂度 | 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;
}
六、常见误区与优化技巧
-
队列溢出:未及时标记已访问节点导致重复入队
-
层级统计错误:未在每层开始时记录队列大小
-
空间浪费:使用额外存储标记访问状态(可直接修改输入矩阵)
-
性能优化:
-
双向BFS减少搜索空间
-
优先队列优化带权图(Dijkstra)
-
位压缩存储状态
-
LeetCode真题训练:
-
200. 岛屿数量
-
279. 完全平方数
-
773. 滑动谜题