题目:VJ
思路:
BFS+回溯,但是要剪枝,看了dalao的题解,超时+WA无数发,终于过了
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<queue>
#include<cmath>
//#include<map>
#include<string>
#include<iostream>
#include<algorithm>
#define INF 0x3f3f3f3f
const int N=300;
using namespace std;
char map[N][N];
char dir[N][N];
int vis[N][N],fx[N][N],fy[N][N];
int n,m,sx,sy,ex,ey,to[4][2]={1,0,-1,0,0,1,0,-1};
char turn[4]={'d','u','r','l'};
struct node{
int x,y;
int step;
int i;
};
queue<node> q;
void init(){
memset (vis,-1,sizeof(vis));
while(!q.empty()) q.pop();
}
int judge(int x,int y,int step){
if(x>=1 && x<=n && y>=1 && y<=m && map[x][y]!='#' && (vis[x][y]==-1 || vis[x][y]==step)) return 1;
return 0;
}
void add(int x,int y,int i,int step){
node a;
x+=to[i][0];
y+=to[i][1];
while(judge(x,y,step)){
if(vis[x][y]!=step){
dir[x][y]=turn[i];
vis[x][y]=step;
fx[x][y]=x-to[i][0];
fy[x][y]=y-to[i][1];
a.i=i;
a.x=x;
a.y=y;
a.step=step;
q.push(a);
}
x+=to[i][0];
y+=to[i][1];
}
}
void paint(int i){
int x,y,tx,ty;
tx=fx[ex][ey];
ty=fy[ex][ey];
x=ex;
y=ey;
while(tx!=sx || ty!=sy){
char wh=dir[tx][ty];
char go=dir[x][y];
if(wh!=go){
if(wh=='u'){
if(go=='l'){
map[tx][ty]='\';
}
else if(go=='r'){
map[tx][ty]='/';
}
}
else if(wh=='d'){
if(go=='r'){
map[tx][ty]='\';
}
else if(go=='l'){
map[tx][ty]='/';
}
}
else if(wh=='l'){
if(go=='u'){
map[tx][ty]='\';
}
else if(go=='d'){
map[tx][ty]='/';
}
}
else if(wh=='r'){
if(go=='d'){
map[tx][ty]='\';
}
else if(go=='u'){
map[tx][ty]='/';
}
}
}
x=tx;
y=ty;
tx=fx[x][y];
ty=fy[x][y];
}
}
void bfs(int dd){
int x,y;
init();
node a,b;
vis[sx][sy]=100000;
dir[sx][sy]='o';
add(sx,sy,dd,0);
while(!q.empty()){
a=q.front();
q.pop();
if(a.x==ex && a.y==ey){
paint(a.i);
return;
}
b.step=a.step+1;
for(int i=0;i<4;i++){
b.x=a.x+to[i][0];
b.y=a.y+to[i][1];
if(judge(b.x,b.y,b.step)){
add(a.x,a.y,i,b.step);
}
}
}
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%s",map[i]+1);
for(int j=1;j<=m;j++){
if(map[i][j]=='C'){
ex=i;ey=j;
}
else if(map[i][j]=='<' || map[i][j]=='>' || map[i][j]=='v' || map[i][j]=='^'){
sx=i;sy=j;
}
}
}
//to[4][2]={1,0, -1,0, 0,1, 0,-1}
int direction;
if(map[sx][sy]=='<') direction=3;
else if(map[sx][sy]=='>') direction=2;
else if(map[sx][sy]=='^') direction=1;
else direction=0;
bfs(direction);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
printf("%c",map[i][j]);
}
printf("
");
}
}
return 0;
}