学完堆以后的第一件事:
2024-07-14 21:00:34
发布于:广东
25阅读
0回复
0点赞
#include <iostream>
#include <cstdio>
//#include <queue>
#include <vector>
using namespace std;
struct Point{
int x, y, step;
};
bool cmp(Point a, Point b){
return a.step < b.step;
}
struct priority_queue{
vector <Point> __data;
void push(Point tmp){
__data.push_back(tmp);
int i = __data.size();
while(i / 2 >= 1 && !cmp(__data[i / 2 - 1], __data[i - 1])){
swap(__data[i - 1], __data[i / 2 - 1]);
i = i / 2;
}
}
Point top(){
return __data[0];
}
void pop(){
__data[0] = __data.back();
__data.pop_back();
int i = 1;
while(i * 2 <= __data.size()){
int j = i * 2;
if(j < __data.size() && cmp(__data[j], __data[j - 1])) j++;
if(!cmp(__data[j - 1], __data[i - 1])) return;
swap(__data[i - 1], __data[j - 1]);
i = j;
}
}
bool empty(){
return __data.empty();
}
int size(){
return __data.size();
}
};
int n, m, x1, y1, x2, y2;
bool vis[45][45];
char mp[45][45];
int dir[4][2] = {-1, 0, 0, -1, 0, 1, 1, 0};
priority_queue q;
bool check(int x, int y){
if(x < 1 || x > n) return 0;
if(y < 1 || y > m) return 0;
if(mp[x][y] == '#') return 0;
if(vis[x][y]) return 0;
return 1;
}
void bfs(int x, int y){
vis[x][y] = 1;
bool flag = 0;
int mx = 0x3f3f3f3f;
q.push({x, y, 0});
while(!q.empty()){
Point head = q.top();
q.pop();
//cout << head.x << ' ' << head.y << ' ' << head.step << endl;
if(head.x == x2 && head.y == y2){
//cout << mx << endl;
mx = min(mx, head.step);
flag = 1;
continue;
}
for(int i = 0; i < 4; i++){
int xx = head.x + dir[i][0], yy = head.y + dir[i][1];
if(check(xx, yy)){
if(mp[xx][yy] != '.' && mp[xx][yy] != 'W') q.push({xx, yy, head.step + 1 + mp[xx][yy] - '0'});
else q.push({xx, yy, head.step + 1});
vis[xx][yy] = 1;
}
}
}
if(!flag) cout << "IMPOSSIBLE";
else cout << mx;
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> mp[i][j];
if(mp[i][j] == 'Z') x1 = i, y1 = j;
if(mp[i][j] == 'W') x2 = i, y2 = j;
}
}//cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << endl;
bfs(x1, y1);
return 0;
}
全部评论 1
你是老师吗
2024-07-14 来自 广东
0不是捏
2024-07-14 来自 广东
0能教道题吗
2024-07-14 来自 广东
0迷宫之最少花费时间?
2024-07-14 来自 广东
0
有帮助,赞一个