Natsu_iiiiro

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2671

#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
#include <math.h>
#include <vector>
using namespace std;

int T;
int r,c;
int vis[1001][1001];
char map[1001][1001];
struct node{
int x,y;
int step;
char flag;
};
queue<node> q;

int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};

int bfs(){
node cur,nex;
while(!q.empty()){
cur = q.front();q.pop();

//printf("cur ::%c :: (%d,%d)\n",cur.flag,cur.x,cur.y);

if(cur.flag == 'J' && (cur.x == 0||cur.x == r-1 || cur.y == 0 || cur.y == c-1) && map[cur.x][cur.y]!='F'){
return cur.step;
}
for(int i = 0;i<4;i++){
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if(nx>=0&&ny>=0&&nx<r&&ny<c && map[nx][ny]!='#'){


if(cur.flag == 'F'&&map[nx][ny]!='F') {
map[nx][ny] = 'F';
//printf("next::%c :: (%d,%d)\n",cur.flag,nx,ny);
nex.x = nx;
nex.y = ny;
nex.step = cur.step+1;
nex.flag = cur.flag;
vis[nx][ny] = 1;
q.push(nex);
}
else if(cur.flag == 'J' && !vis[nx][ny]){
//printf("next::%c :: (%d,%d)\n",cur.flag,nx,ny);
nex.x = nx;
nex.y = ny;
nex.step = cur.step+1;
nex.flag = cur.flag;
vis[nx][ny] = 1;
q.push(nex);
}
}

}

}
return -1;
}
int main(){
int T;
int res;
scanf("%d",&T);
while(T--){
memset(vis,0,sizeof vis);
memset(map,0,sizeof map);
while(!q.empty()) q.pop();
scanf("%d%d",&r,&c);

//Input
for(int i = 0;i<r;i++){
scanf("%s",map[i]);
//直接把J和F放进的队列然后像一般的bfs来搞就好了,没什么需要特别注意的地方
for(int j = 0;j<c;j++){
if(map[i][j] == 'J'){
node s;
s.flag = 'J';
s.x = i;
s.y = j;
s.step = 0;
q.push(s);
vis[i][j] = 1;
}else if(map[i][j] == 'F'){
node s;
s.flag = 'F';
s.x = i;
s.y = j;
s.step = 0;
q.push(s);
vis[i][j] = 1;
}
}
}
//Input End;
res = bfs();
if(res == -1) printf("IMPOSSIBLE\n");
else printf("%d\n",res+1);
}
return 0;
}

posted on 2019-03-29 13:24  Natsu_iiiiro  阅读(176)  评论(0编辑  收藏  举报