5 5 **..T **.*. ..|.. .*.*. S....
7地图如下:HintHint
#include <stdio.h>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <vector>
using namespace std;
int n,m,x2,y2;
char mat[25][25];
//int vis[25][25];
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
int pre[25][25];
struct node
{
int x,y;
int step;
bool friend operator<(node pp,node o)
{
return pp.step>o.step;
}
};
bool check(node a)
{
if(a.x<0 || a.y<0 ||a.x>=n ||a.y>=m ||mat[a.x][a.y]=='*' ||pre[a.x][a.y]&&pre[a.x][a.y]<=a.step) //走过的点可以再走。所以不用开vis数组来标记,用步数来标记就好,前提是下一步走到这里要比前一步走到这里的步数要少
return 0;
return 1;
}
int bfs(int x,int y)
{
int i,p,l;
priority_queue<node>q;
node st,ed;
st.x=x;
st.y=y;
st.step=0;
q.push(st);
while(!q.empty())
{
st=q.top();
q.pop();
if(st.x==x2 &&st.y==y2 &&mat[st.x][st.y]=='T')
return st.step;
for(i=0; i<4; i++)
{
ed.x=st.x+dir[i][0];
ed.y=st.y+dir[i][1];
ed.step=st.step+1;
if(mat[ed.x][ed.y]=='|')
{
if(ed.x==st.x &&((st.step)&1==0))//左右走,且梯子为“|”; 上楼梯
ed.step+=1;
if(ed.y==st.y&&((st.step)&1==1)) //上下走,且梯子为"-",往其他地方走。
ed.step+=1;
ed.x+=dir[i][0];
ed.y+=dir[i][1];
}
else if(mat[ed.x][ed.y]=='-')
{
if(ed.x==st.x &&((st.step)&1==1))//左右走,且梯子为“|”;,往其他地方走。
ed.step+=1;
if(ed.y==st.y&&((st.step)&1==0)) //上下走,且梯子为"-" 上楼梯
ed.step+=1;
ed.x+=dir[i][0];
ed.y+=dir[i][1];
}
/*
if(mat[ed.x+1][ed.y]=='|')
ed.x=ed.x+2;
else if(mat[ed.x-1][ed.y]=='|')
ed.x=ed.x-2;
else if(mat[ed.x][ed.y+1]=='-')
ed.y=ed.y+2;
else if(mat[ed.x][ed.y-1]=='-')
ed.y=ed.y-2;
*/
if(!check(ed))
continue;
pre[ed.x][ed.y]=ed.step;
//vis[ed.x][ed.y]=1;
/*
for(p=0; p<n; p++)
for(l=0; l<m; l++)
{
if(mat[p][l]=='|')
mat[p][l]='-';
else if(mat[p][l]=='-')
mat[p][l]='|';
}
*/
q.push(ed);
// cout<<ed.step<<endl;
}
}
return -1;
}
int main()
{
int x1,y1;
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,j;
// memset(vis,0,sizeof(vis));
memset(pre,0,sizeof(pre));
for(i=0; i<n; i++)
{
scanf("%s",mat[i]);
for(j=0; j<m; j++)
{
if(mat[i][j]=='S')
{
x1=i;
y1=j;
}
else if(mat[i][j]=='T')
{
x2=i;
y2=j;
}
}
}
// vis[x1][y1]=1;
int ans=bfs(x1,y1);
cout<<ans<<endl;
}
return 0;
}
原文:http://blog.csdn.net/sky_miange/article/details/44905863