Consider an N x N (1 <= N <= 100) square field composed of 1
by 1 tiles. Some of these tiles are impassible by cows and are marked with an ‘x’ in this 5 by 5 field that is challenging to navigate:
. . B x .
. x x A .
. . . x .
. x . . .
. . x . .
Bessie finds herself in one such field at location A and wants to move to location B in order to lick the salt block there. Slow, lumbering creatures like cows do not like to turn and, of course, may only move parallel to the edges of the square field. For a given field, determine the minimum number of ninety degree turns in any path from A to B. The path may begin and end with Bessie facing in any direction. Bessie knows she can get to the salt lick.
N*N(1<=N<=100)方格中,’x’表示不能行走的格子,’.’表示可以行走的格子。卡门很胖,故而不好转弯。现在要从A点走到B点,请问最少要转90度弯几次?
输入格式
第一行一个整数N,下面N行,每行N个字符,只出现字符:’.’,’x’,’A’,’B’,表示上面所说的矩阵格子,每个字符后有一个空格。
【数据规模】
2<=N<=100
输出格式
一个整数:最少转弯次数。如果不能到达,输出-1。
输入输出样例
输入 #1复制
3
. x A
. . .
B x .
输出 #1复制
2
说明/提示
【注释】
只可以上下左右四个方向行走,并且不能走出这些格子之外。开始和结束时的方向可以任意。
思路
BFS模板,按照四个方向搜到底即可
# include<iostream>
# include<algorithm>
# include<cmath>
# include<cstdio>
# include<set>
# include<stack>
# include<queue>
# include<map>
# include<string>
# include<cstring>
using namespace std;
typedef long long ll;
const ll mod=1000;
const int MAX=1e6+5;
const int Time=86400;
const double pir=3.14159265358979323;
struct Node{
int x;
int y;
int step;
};
int n,sx,sy;
int vis[105][105];
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
char a[105][105];
queue<Node>q;
void bfs(int x,int y){
q.push({x,y,0});
vis[x][y] = 1;
while(q.size()){
Node now = q.front() ;
q.pop();
for(int i=0;i<4;i++){ //四个方向
for(int j=1;;j++){ //每个方向搜到底
int xx = j*dx[i] + now.x;
int yy = j*dy[i] + now.y;
if(xx==sx&&yy==sy){ //到达
cout<<now.step ;
exit(0);
}
if(xx<1 || xx>n || yy<1 || yy>n || a[xx][yy]!='.') break; //越界
if(xx>=1&&xx<=n&&yy>=1&&yy<=n&&a[xx][yy]=='.'){
if(vis[xx][yy]) continue;
vis[xx][yy]=1;
q.push({xx,yy,now.step +1 });
}
}
}
}
cout<<-1;
return ;
}
int main(){
cin>>n;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j){
cin>>a[i][j];
if(a[i][j]=='B')
sx=i,sy=j,a[i][j]='.';
}
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
if(a[i][j]=='A') a[i][j]='.',bfs(i,j); //有就bfs
return 0;
}