hdu 1242 找到朋友最短的时间 (BFS+优先队列)

找到朋友的最短时间

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 * 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 * all his life.\n") ; } return ;
}
上一篇:BFS+优先队列+状态压缩DP+TSP


下一篇:iOS开发-UIApplication和App启动状态