您现在的位置是:主页 > news > 未央免费做网站/赚钱平台

未央免费做网站/赚钱平台

admin2025/4/30 4:15:27news

简介未央免费做网站,赚钱平台,服务器安全卫士,wordpress用户发文章数量bfs有一个通用的模板&#xff0c;1. 初始值加入队列。2. 队列非空时&#xff0c;取队头元素。将其可到达的元素加入队列。&#xff08;无权重时&#xff09; 算法模板 例&#xff1a;Acwing844 #include <iostream> #include <algorithm> #include <queue>…

未央免费做网站,赚钱平台,服务器安全卫士,wordpress用户发文章数量bfs有一个通用的模板&#xff0c;1. 初始值加入队列。2. 队列非空时&#xff0c;取队头元素。将其可到达的元素加入队列。&#xff08;无权重时&#xff09; 算法模板 例&#xff1a;Acwing844 #include <iostream> #include <algorithm> #include <queue>…

bfs有一个通用的模板,1. 初始值加入队列。2. 队列非空时,取队头元素。将其可到达的元素加入队列。(无权重时

算法模板

例:Acwing844

#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>using namespace std;typedef pair<int, int> PII;const int N = 110;int n, m;
int g[N][N];
int d[N][N];
queue<PII> q;
PII Prev[x][y];int bfs()
{memset(d, -1, sizeof d);int dx[4] = { -1, 0, 1, 0}, dy[4] = { 0, 1, 0, -1 };// 初始值加入队列q.push(make_pair(0, 0));d[0][0]=0;while (!q.empty())  // 队列不为空{  // 取出队头元素auto t = q.front();    q.pop();for (int i = 0; i < 4; ++i){   // 将下一层元素加入队尾int x = t.first + dx[i], y = t.second + dy[i];if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1){d[x][y] = d[t.first][t.second] + 1;Prev[x][y] = t;q.push(make_pair(x, y));}}}
int x = n - 1, y = m - 1;
while (x || y)
{cout << x << " " << y;auto t = Prev[x][y];x = t.first, y = t.second;
} return d[n - 1][m - 1];
}int main()
{cin >> n >> m;for (int i = 0; i < n; ++i)for (int j = 0; j < m; ++j)cin >> g[i][j];cout << bfs() << endl;return 0;
}

一个带权重例子

Acwing845. 八数码

/*
BFS1. 状态表示复杂。队列?2. 如何记录每一个状态的距离
*/#include <cstring>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <string>
#include <queue>using namespace std;
typedef pair<string, int> PSI;int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};const int N = 10;
int g[N];int bfs(string start)
{string end = "12345678x";queue<string> q;unordered_map<string, int> d;q.push(start);d[start] = 0;while (q.size()){auto t = q.front();q.pop();int distance = d[t];// 如果到达最终状态,则输出步数if (t == end) return distance;// 状态转移int k = t.find('x');int x = k / 3, y = k % 3;for (int i = 0; i < 4; ++i){int a = x + dx[i], b = y + dy[i];if (a >= 0 && a < 3 && b >= 0 && b < 3){// a * 3 + b 将二维的转化维三维的swap(t[k], t[a * 3 + b]);if (!d.count(t)){d[t] = distance + 1;q.push(t);}swap(t[k], t[a * 3 + b]);}}}return -1;
}int main()
{string start;for (int i = 0; i < 9; ++i){char c;cin >> c;start += c;}cout << bfs(start) << endl;return 0;
}