添加bfs

This commit is contained in:
zhuyijun 2021-11-14 16:37:17 +08:00
parent 691f54b150
commit b63a62fad1
4 changed files with 140 additions and 1 deletions

View File

@ -85,6 +85,7 @@
"barrier": "cpp",
"latch": "cpp",
"semaphore": "cpp",
"syncstream": "cpp"
"syncstream": "cpp",
"queue": "cpp"
}
}

61
bfs/111.cpp Normal file
View File

@ -0,0 +1,61 @@
/*
* @Description:
* @Version: 1.0
* @Autor: zhuyijun
* @Date: 2021-11-13 16:39:27
* @LastEditTime: 2021-11-14 15:11:24
*/
/*
1
root = [3,9,20,null,null,15,7]
2
2
root = [2,null,3,null,4,null,5,null,6]
5
*/
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right)
: val(x), left(left), right(right) {}
};
int minDepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
queue<TreeNode> q;
q.push(*root);
int depth = 1;
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
//获取队列第一位元素
TreeNode cur = q.front();
//移除队列中第一位元素
q.pop();
if (cur.left == nullptr && cur.right == nullptr) {
return depth;
}
if (cur.left != nullptr) {
q.push(*cur.left);
}
if (cur.right != nullptr) {
q.push(*cur.right);
}
}
depth++;
}
return depth;
}
int main() { return 0; }

76
bfs/752.cpp Normal file
View File

@ -0,0 +1,76 @@
/*
* @Description:
* @Version: 1.0
* @Autor: zhuyijun
* @Date: 2021-11-14 15:33:16
* @LastEditTime: 2021-11-14 16:30:35
*/
#include <bits/stdc++.h>
using namespace std;
string plusOne(string s, int j) {
if (s[j] == '9') {
s[j] = '0';
} else {
s[j] += 1;
}
return s;
}
string minusOne(string s, int j) {
if (s[j] == '0') {
s[j] = '9';
} else {
s[j] -= 1;
}
return s;
}
int openLock(vector<string>& deadends, string target) {
set<string> deads;
deads.insert(deadends.begin(), deadends.end());
// for (string s : deadends) {
// deads.insert(s);
// }
//记录已经穷举过得密码,防止走回头路
set<string> visited;
int step = 0;
queue<string> q;
q.push("0000");
visited.insert("0000");
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
string cur = q.front();
q.pop();
cout << cur << endl;
//判断是否达到终点
if (deads.find(cur) != deads.end()) {
continue;
}
if (cur == target) {
return step;
}
for (int j = 0; j < 4; j++) {
string up = plusOne(cur, j);
if (visited.find(up) == visited.end()) {
q.push(up);
visited.insert(up);
}
string down = minusOne(cur, j);
if (visited.find(down) == visited.end()) {
q.push(down);
visited.insert(down);
}
}
}
//增加步数
step++;
}
return -1;
}
int main() {
vector<string> deadends{"0201", "0101", "0102", "1212", "2002"};
string s = "0202";
cout << openLock(deadends, s);
return 0;
}

View File

@ -60,6 +60,7 @@ vector<vector<int>> permute(vector<int>& nums) {
}
//测试
int main() {
vector<int> nums;
nums.push_back(1);