BFS参考:https://mp.weixin.qq.com/s/WH_XGm1-w5882PnenymZ7g
题目:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
广度优先搜索本质,层层推进。我写的注释很详细,好好理解!
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL) return 0;
queue<TreeNode*> q;
q.push(root);
//root本身就是1层,初始化为1
int depth = 1;
//此时q中仅仅保存着同一层的所有节点,depth是当前层的深度
while(!q.empty()) {
int nums = q.size();
//将当前层的所有节点向四周扩散
for(int i = 0; i < nums; i++) {
TreeNode* curr = q.front();
q.pop();
// 判断是否到达叶子节点
if(curr->left == NULL && curr->right == NULL)
return depth;
// 将curr的相邻节点(二叉树就是左右子节点)加入队列
if(curr->left != NULL)
q.push(curr->left);
if(curr->right != NULL)
q.push(curr->right);
}
// 把下一层的所有节点都加入队列后,深度加1
depth++;
}
return depth;
}
};
题目:https://leetcode-cn.com/problems/open-the-lock/
class Solution_752 {
public:
// string S 第 i 个位置加1
string plusOne(string S, int i) {
string res(S);
if(res[i] == '9')
res[i] = '0';
else
res[i] += 1;
return res;
}
string minusOne(string S, int i) {
string res(S);
if(res[i] == '0')
res[i] = '9';
else
res[i] -= 1;
return res;
}
int openLock(vector<string>& deadends, string target) {
//记录要跳过的密码
set<string> deadChoose(deadends.begin(), deadends.end());
//记录已经穷举过的密码, 防止走回头路
set<string> visited;
//从起点开始启动广度优先搜索
queue<string> q;
q.push("0000");
visited.insert("0000");
int step = 0;
//此时q中仅仅保存着同一层的所有节点, step是从最开始变到当前层的操作数
while(!q.empty()) {
int nums = q.size();
//将当前层的所有节点向周围扩散
for (int i = 0; i < nums; ++i) {
string curr = q.front();
q.pop();
if(deadChoose.find(curr) != deadChoose.end())
continue; //这种情况不予考虑
if(curr == target)
return step;
//将一个节点的未遍历相邻节点加入队列
for (int j = 0; j < 4; ++j) {
string up = plusOne(curr, j);
string down = minusOne(curr, j);
if(visited.find(up) == visited.end()) {
q.push(up);
visited.insert(up);
}
if(visited.find(down) == visited.end()) {
q.push(down);
visited.insert(down);
}
}
}
//把下一层的所有节点都加入队列后, 操作数加1
step++;
}
// 如果穷举完都没找到目标密码,那就是找不到了
return -1;
}
};