广搜题 很生 。
qx表示横坐标 qy表示纵坐标 qd表示方向 其他的看代码吧
代码如下
#include<iostream>
#include<cstdio>
#include<cctype>
#include<queue>
#include<cstdlib>
using namespace std;
#define in = read();
typedef long long ll;
typedef unsigned int ui;
const ll size = 50 + 5;
queue<int>qx , qy , qd;
int n , m;
int sx , sy , tx , ty , num , x , y , d , x1 , y1 , d1;
int a[size][size][size];
bool map[size][size];
int heng[4] = {0 , 1 , 0 , -1} , shu[4] = {1 , 0 , -1 , 0};
char c;
inline ll read(){
ll num = 0 , f = 1; char ch = getchar();
while(!isdigit(ch)){
if(ch == '-') f = -1;
ch = getchar();
}
while(isdigit(ch)){
num = num*10 + ch - '0';
ch = getchar();
}
return num*f;
}
inline void bfs(){
while(!qx.empty()){
x = qx.front(); y = qy.front(); d = qd.front();
qx.pop(); qy.pop(); qd.pop();
for(register int i=1;i<=3;i++){
x1 = x + heng[d]*i;
y1 = y + shu[d]*i;
if(x1 <= 0 || x1 >= n || y1 <= 0 || y1 >= m || map[x1][y1]) break;
if(x1 == tx && y1 == ty){
printf("%d" , a[x][y][d]);
exit(0);
}
if(!a[x1][y1][d]){
a[x1][y1][d] = a[x][y][d] + 1;
qx.push(x1); qy.push(y1); qd.push(d);
}
}
d1 = d + 1;
if(d1 == 4) d1 = 0;
if(!a[x][y][d1]){
a[x][y][d1] = a[x][y][d] + 1;
qx.push(x); qy.push(y); qd.push(d1);
}
if(!d) d1 = 3;
else d1 = d - 1;
if(!a[x][y][d1]){
a[x][y][d1] = a[x][y][d] + 1;
qx.push(x); qy.push(y); qd.push(d1);
}
}
}
int main(){
n in; m in;
for(register int i=1;i<=n;i++)
for(register int j=1;j<=m;j++){
num in;
if(num) map[i][j] = map[i - 1][j - 1] = map[i - 1][j] = map[i][j - 1] = 1;
}
sx in; sy in; tx in; ty in; cin>>c;
if(sx == tx && sy == ty){
printf("0");
return 0;
}
if(map[tx][ty]){
printf("-1");
return 0;
}
qx.push(sx); qy.push(sy);
if(c == 'E') a[sx][sy][0]=1 , qd.push(0);
else if(c == 'S') a[sx][sy][1]=1 , qd.push(1);
else if(c == 'W') a[sx][sy][2]=1 , qd.push(2);
else if(c == 'N') a[sx][sy][3]=1 , qd.push(3);
bfs();
printf("-1");
return 0;
}
//COYG