题目地址:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=25&page=show_problem&problem=2327
题目大意:王不可以走到马一步所能走到的位置上,终点除外,求最短路长度
解题方法:标准BFS
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <queue>
using namespace std;
#define MAXN 110
int map[MAXN][MAXN],map2[MAXN][MAXN],book[MAXN*MAXN];
char cmap[MAXN][MAXN];
const int N=105;
const int hd[8][2]={{-2,-1},{-1,-2},{-2,1},{-1,2},{2,-1},{1,-2},{2,1},{1,2}};
const int kd[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
const int INF=0x3f3f3f3f;
int main()
{
int t;cin>>t;
while(t--)
{
memset(map,-1,sizeof(map));
memset(map2,-1,sizeof(map2));
int m,n;cin>>m>>n;getchar();
int start,finish,zx,zc;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
char ch=getchar();
if(ch=='.')map[i][j]=0;
else if(ch=='Z'){map[i][j]=1;map2[i][j]=1;}
else if(ch=='A'){map[i][j]=0;start=i*n+j;}
else if(ch=='B'){map[i][j]=0;finish=i*n+j;zx=i;zc=j;}
}
getchar();
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(map2[i][j]==1)
{
for(int qw=0;qw<8;qw++)
{
int dx=i+hd[qw][0],dy=j+hd[qw][1];
if(dx>=0&&dx<m&&dy>=0&&dy<n)map[dx][dy]=1;
}
}
}
}
map[zx][zc]=0;
/*for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout<<map[i][j]<<" ";
}
cout<<endl;
}*/
queue<int>q;
memset(book,-1,sizeof book);
q.push(start);book[start]=0;
while (!q.empty())
{
int u=q.front();
q.pop();
if (u==finish)break;
int x=u/n;
int y=u%n;
for (int i=0;i<8;i++)
{
int dx=x+kd[i][0],dy=y+kd[i][1];
int v=dx*n+dy;
if (dx>=0&&dx<m&&dy>=0&&dy<n&&map[dx][dy]==0&&book[v]==-1)
{
book[v]=book[u]+1;
q.push(v);
}
}
}
/*for(int i=0;i<m*n;i++)
{
cout<<book[i]<<" ";
if((i+1)%n==0)cout<<endl;
}*/
if(book[finish]==-1)cout<<"King Peter, you can't go now!"<<endl;
else cout<<"Minimal possible length of a trip is "<<book[finish]<<endl;
}
return 0;
}