注意一点的是可以停留,但实际上是在第一次到达时选择停留还是不停留,这样是一个剪枝
AC代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct Node{
int x, y;
int step;
};
char maps[22][22];
int M, N;
Node st, ed;
int moves[][2] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
int BFS(){
int mark[22][22];
memset( mark, 0x3f, sizeof( mark ) );
queue<Node> q;
q.push( st );
mark[st.x][st.y] = 0;
bool tt[22][22];
memset( tt, false, sizeof( tt ) );
while( !q.empty() ){
Node n = q.front();
q.pop();
if( !tt[n.x][n.y] ){
Node temp = n;
temp.step++;
q.push( temp );
tt[n.x][n.y] = true;
}
if( n.x == ed.x && n.y == ed.y ){
return n.step;
}
for( int k = 0; k < 4; k++ ){
Node temp = n;
temp.x += moves[k][0];
temp.y += moves[k][1];
temp.step++;
if( maps[temp.x][temp.y] == '*' || temp.x < 0 || temp.x >= M || temp.y < 0 || temp.y >= N ){
continue;
}else if( maps[temp.x][temp.y] == '|' ){
if( k == 0 ){
if( ( temp.step - 1 ) % 2 == 0 ){
continue;
}else{
temp.y += 1;
}
}else if( k == 1 ){
if( ( temp.step - 1 ) % 2 == 0 ){
continue;
}else{
temp.y -= 1;
}
}else if( k == 2 ){
if( ( temp.step - 1 ) % 2 == 0 ){
temp.x += 1;
}else{
continue;
}
}else{
if( ( temp.step - 1 ) % 2 == 0 ){
temp.x -= 1;
}else{
continue;
}
}
}else if( maps[temp.x][temp.y] == '-' ){
if( k == 0 ){
if( ( temp.step - 1 ) % 2 == 0 ){
temp.y += 1;
}else{
continue;
}
}else if( k == 1 ){
if( ( temp.step - 1 ) % 2 == 0 ){
temp.y -= 1;
}else{
continue;
}
}else if( k == 2 ){
if( ( temp.step - 1 ) % 2 == 0 ){
continue;
}else{
temp.x += 1;
}
}else{
if( ( temp.step - 1 ) % 2 == 0 ){
continue;
}else{
temp.x -= 1;
}
}
}
if( mark[temp.x][temp.y] <= temp.step ){
continue;
}
q.push( temp );
mark[temp.x][temp.y] = temp.step;
}
}
return -1;
}
int main(){
while( scanf( "%d%d", &M, &N ) != EOF ){
for( int i = 0; i < M; i++ ){
scanf( "%s", maps[i] );
for( int j = 0; j < N; j++ ){
if( maps[i][j] == 'S' ){
st.x = i;
st.y = j;
st.step = 0;
}else if( maps[i][j] == 'T' ){
ed.x = i;
ed.y = j;
ed.step = 0;
}
}
}
cout << BFS() << endl;
}
return 0;
}
594




被折叠的 条评论
为什么被折叠?



