hdu-1242 Rescue
本题用到了了搜索和队列,第一次将这两个加起来写,有点吃力。。。。。。
队列相关知识:http://blog.csdn.net/zxy_snow/article/details/6118988
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
int map[220][220];
int a_x,a_y,b_x,b_y,n,m;
int top[4][2]={{0,-1},{0,1},{1,0},{-1,0}}; //上下搜索的四个点
struct node{//自定义的队列
int x; int y;
int step;
friend bool operator < (node n1,node n2){
return n2.step < n1.step;
}
};
int judge(int x,int y){//判断执行条件
if(x < 0 || x >= n || y < 0 || y >= m)
return 1;
if(map[x][y] == 1)
return 1;
return 0;
}
int bfs(){//搜索
priority_queue<node>q;
node cur,next;
int i;
cur.x = b_x;
cur.y = b_y;
cur.step = 0;
map[cur.x][cur.y] = 1;
q.push(cur);
while(!q.empty()){
cur = q.top();
q.pop();
if(cur.x == a_x && cur.y == a_y)
return cur.step;
for(i = 0;i < 4;i++){
next.x = cur.x + top[i][0];
next.y = cur.y + top[i][1];
if(judge(next.x,next.y))
continue;
if(map[next.x][next.y] == -1)
next.step = cur.step + 2;
else
next.step = cur.step + 1;
map[next.x][next.y] = 1;
q.push(next);
}
}
return -1;
}
int main(){
int i,j,k,t;
char str[220];
while(~scanf("%d %d",&n,&m)){
memset(map,0,sizeof(map));
for(i=0;i<n;i++){
scanf("%s",str);
for(j=0;str[j];j++){
if(str[j] == 'a'){//标记带搜索的位置
a_x = i;
a_y = j;
}
else if(str[j] == 'r'){//标记开始搜索的位置
b_x = i;
b_y = j;
}
else if(str[j] == '#')
map[i][j] = 1;//将为墙的标记为1
else if(str[j] == '.')
map[i][j] = 0;//将为道路的标记为0
else if(str[j] == 'x')
map[i][j] = -1;//将为敌人的标记为-1
}
}
int ans = bfs();
if(ans == -1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n",ans);
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理