hdu 1242 找到朋友最短的时间 (BFS+优先队列)
2024-10-16 06:26:46
找到朋友的最短时间
Sample Input
7 8
#.#####. //#不能走 a起点 x守卫 r朋友
#.a#..r. //r可能不止一个
#..#x...
..#..#.#
#...##..
.#......
........
Sample Output
13
bfs+优先队列
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std; int n, m;
char map[][];
int sx, sy;
bool flag; struct node
{
int x , y , step ;
bool operator <(const node &t) const
{
return step > t.step ;
}
}; int dx[] = {,,,-} ;
int dy[] = {,-,,} ; void bfs()
{
node now , t ;
int i , fx ,fy ;
priority_queue<node> q ;
now.x = sx ;
now.y = sy ;
now.step = ;
q.push(now) ;
map[sx][sy] = '#' ;
while(!q.empty())
{
now = q.top() ;
q.pop() ;
for (i = ; i < ; i++)
{
fx = now.x + dx[i] ;
fy = now.y + dy[i] ;
if (fx< || fy< || fx >=n || fy >=m ||map[fx][fy] == '#')
continue ;
if (map[fx][fy] == 'r')
{
printf("%d\n" , now.step+) ;
flag = ;
return ;
}
if (map[fx][fy] == 'x')
{
t.x = fx ;
t.y = fy ;
t.step = now.step + ;
q.push(t) ;
}
else
{
t.x = fx ;
t.y = fy ;
t.step = now.step + ;
q.push(t) ;
}
map[fx][fy] = '#' ; }
} } int main()
{
// freopen("in.txt","r",stdin) ;
while (scanf("%d %d" , &n , &m) !=EOF)
{
int i , j ;
for (i = ; i < n ; i++)
{
for (j = ; j < m ; j++)
{
cin>>map[i][j] ;
if (map[i][j] == 'a')
{
sx = i ;
sy = j ;
}
}
}
flag = ;
bfs() ;
if (!flag)
printf("Poor ANGEL has to stay in the prison all his life.\n") ;
} return ;
}
dfs
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std; char map[][] ;
bool visit[][] ; int n , m ;
int MIN ; void dfs(int x , int y , int sum)
{
if (x< || y< || x>= n || y>= m)
return ;
if (map[x][y] == '#')
return ;
if (sum >= MIN)
return ;
if (visit[x][y] == )
return ;
if (map[x][y] == 'r')
{
if (sum < MIN)
MIN = sum ;
return ;
}
if (map[x][y] == 'x')
sum++ ;
visit[x][y] = ;
dfs(x+,y,sum+) ;
dfs(x-,y,sum+) ;
dfs(x,y+,sum+) ;
dfs(x,y-,sum+) ;
visit[x][y] = ;
} int main()
{
// freopen("in.txt","r",stdin) ; while (scanf("%d %d" , &n , &m) !=EOF)
{
if (n == && m == )
break ;
memset(visit , ,sizeof(visit)) ;
int i , j ;
int bx , by ;
int sum = ; for (i = ; i < n ; i++)
{
for (j = ; j < m ; j++)
{
cin>>map[i][j];
if (map[i][j] == 'a')
{
bx = i ;
by = j ; }
} } MIN = INT_MAX ;
dfs(bx,by,sum) ;
if (MIN != INT_MAX)
printf("%d\n" , MIN) ;
else
printf("Poor ANGEL has to stay in the prison all his life.\n") ; } return ;
}
最新文章
- HTML5开发笔记:图片上传预览
- javascript基础03
- javaScript 相关笔记
- ACM: Happy 2004-数论专题-因子求和-快速幂
- ecshop的订单状态
- PHP使用DateTime类做时间日期到字符串转换
- 转载:node.js socket.io
- LR之面向目标场景
- Ubuntu中wine安装的程序如何卸载
- cookie、localStorage、sessionStorage之间的区别
- jquery自适应布局
- Jquery案例——某网站品牌列表的效果
- HTML5API___Web Storage
- 自定义NSOperation
- Cdoefroces #354
- RabbitMQ消息队列(九)-通过Headers模式分发消息(.Net Core版)
- BMP文件解析
- 洛谷P5072 [Ynoi2015]盼君勿忘 [莫队]
- mongo3.x配置说明
- dxCameraControl控件(拍照)