社区讨论
双端队列BFS模板题求助!
灌水区参与者 1已保存回复 0
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @m3yktbng
- 此快照首次捕获于
- 2024/11/26 22:52 去年
- 此快照最后确认于
- 2024/11/27 08:24 去年
CPP
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node{
int x,y;
node(int xx,int yy) {
x = xx;
y = yy;
return;
}
};
int n,m,dx[4] = {-1,-1,1,1},dy[4] = {-1,1,-1,1},cdx[4] = {0,0,1,1},cdy[4] = {0,1,0,1};
ll dis[510][510];
char g[510][510],dir[4] = {'\\','/','/','\\'};
deque<node> q;
void bfs() {
memset(dis,0x3f,sizeof(dis));
q.push_back(node(0,0));
dis[0][0] = 0;
while (!q.empty()) {
int ux = q.front().x,uy = q.front().y;
q.pop_front();
for (int i = 0;i < 4;i ++) {
int vx = ux + dx[i],vy = ux + dy[i];
if (vx >= 0 && vx <= n && vy >= 0 && vy <= m) {
int w = g[ux + cdx[i]][uy + cdy[i]] != dir[i];
if (dis[vx][vy] > dis[ux][uy] + w) {
dis[vx][vy] = dis[ux][uy] + w;
if (w) q.push_back(node(vx,vy));
else q.push_front(node(vx,vy));
if (vx == n && vy == m) break;
}
}
}
}
return;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 1;i <= n;i ++)
for (int j = 1;j <= m;j ++)
cin >> g[i][j];
bfs();
// for (int i = 0;i <= n;i ++) {
// for (int j = 0;j <= m;j ++)
// if (dis[i][j] >= 0x3f3f3f3f3f3f3f3fll) cout << "inf\t";
// else cout << dis[i][j] << "\t";
// cout << "\n";
// }
if (dis[n][m] >= 0x3f3f3f3f3f3f3f3fll) cout << "NO SOLUTION\n";
else cout << dis[n][m] << "\n";
return 0;
}
回复
共 0 条回复,欢迎继续交流。
正在加载回复...