P1649 [USACO07OCT]障碍路线Obstacle Course
题目描述
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。
输入输出样例
说明
【注释】
只可以上下左右四个方向行走,并且不能走出这些格子之外。开始和结束时的方向可以任意。
这里注意跟朴素bfs不同在于
while不停入队和vis打标记
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define inf 2147483647 const ll INF = 0x3f3f3f3f3f3f3f3fll; #define ri register int template <class T> inline T min(T a, T b, T c) { return min(min(a, b), c); } template <class T> inline T max(T a, T b, T c) { return max(max(a, b), c); } template <class T> inline T min(T a, T b, T c, T d) { return min(min(a, b), min(c, d)); } template <class T> inline T max(T a, T b, T c, T d) { return max(max(a, b), max(c, d)); } #define pi acos(-1) #define me(x, y) memset(x, y, sizeof(x)); #define For(i, a, b) for (int i = a; i <= b; i++) #define FFor(i, a, b) for (int i = a; i >= b; i--) #define mp make_pair #define pb push_back const int maxn = 100005; #define mod 100003 const int N=200; // name******************************* struct node { int x,y; } p[N]; int dx[4]= {1,-1,0,0}; int dy[4]= {0,0,1,-1}; queue<node>que; bool vis[N][N]; char G[N][N]; int n; node sx,ex; int cnt[N][N]; // function****************************** void bfs(node u) { que.push(u); vis[u.x][u.y]=1; while(!que.empty()) { node t=que.front(); que.pop(); int x=t.x,y=t.y; For(i,0,3) { int tx=x+dx[i],ty=y+dy[i]; if(tx<1||tx>n||ty<1||ty>n)continue; while((G[tx][ty]=='.'||G[tx][ty]=='B'))//vis的判断条件不能加在这里!!就算这点走过了,但这一行或这一列其他点不一定走过!!while需要继续搜 { if(vis[tx][ty]==0) { que.push(node{tx,ty}); vis[tx][ty]=1; cnt[tx][ty]=cnt[x][y]+1; } if(tx==ex.x&&ty==ex.y) { cout<<cnt[tx][ty]; exit(0); } tx+=dx[i],ty+=dy[i]; } } } } //*************************************** int main() { // freopen("test.txt", "r", stdin); cin>>n; For(i,1,n) For(j,1,n) { cin>>G[i][j]; if(G[i][j]=='A') { sx.x=i,sx.y=j; cnt[i][j]=-1; } if(G[i][j]=='B') ex.x=i,ex.y=j; } bfs(sx); cout<<-1; return 0; }