題目描述
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。
輸入輸出樣例
3 . x A . . . B x .
2
說明
【注釋】
只可以上下左右四個方向行走,並且不能走出這些格子之外。開始和結束時的方向可以任意。
1//我用的DFS,他們說dfs做不出來,但我做出來了QWQ
#include<bits/stdc++.h> 2 using namespace std; 3 int read() 4 { 5 int ret=0,ok=1;char ch=getchar(); 6 while(ch<'0'||ch>'9') {if(ch=='-')ok=-1;ch=getchar();} 7 for(;ch>='0'&&ch<='9';ch=getchar()) ret=ret*10+ch-'0'; 8 return ret*ok; 9 } 10 int n; 11 char a[105][105]; 12 int ans[105][105]; 13 bool vis[105][105],sea[105][105]; 14 int bx[]={-1,1,0,0}; 15 int by[]={0,0,-1,1}; 16 inline void dfs(int sx,int sy) 17 { 18 sea[sx][sy]=true; 19 if(sx>n || sy>n || sy<=0 || sx<=0) 20 return; 21 vis[sx][sy]=1; 22 for(int i=sx+1;i<=n;i++) 23 { 24 if(a[i][sy]=='x') 25 break; 26 if(ans[i][sy]>ans[sx][sy]+1) 27 { 28 ans[i][sy]=ans[sx][sy]+1; 29 dfs(i,sy); 30 } 31 vis[i][sy]=true; 32 } 33 for(int i=sx-1;i>=1;i--) 34 { 35 if(a[i][sy]=='x') 36 break; 37 if(ans[i][sy]>ans[sx][sy]+1) 38 { 39 ans[i][sy]=ans[sx][sy]+1; 40 dfs(i,sy); 41 } 42 vis[i][sy]=true; 43 } 44 for(int i=sy+1;i<=n;i++) 45 { 46 if(a[sx][i]=='x') 47 break; 48 if(ans[sx][i]>ans[sx][sy]+1) 49 { 50 ans[sx][i]=ans[sx][sy]+1; 51 dfs(sx,i); 52 } 53 vis[sx][i]=true; 54 } 55 for(int i=sy-1;i>=1;i--) 56 { 57 if(a[sx][i]=='x') 58 break; 59 if(ans[sx][i]>ans[sx][sy]+1) 60 { 61 ans[sx][i]=ans[sx][sy]+1; 62 dfs(sx,i); 63 } 64 vis[sx][i]=true; 65 } 66 for(int i=1;i<=4;i++) 67 { 68 int nx=sx+bx[i]; 69 int ny=sy+by[i]; 70 if(nx>n || ny>n || ny<=0 || nx<=0) 71 continue; 72 if(vis[nx][ny] && !sea[nx][ny]) 73 { 74 sea[nx][ny]=1; 75 dfs(nx,ny); 76 } 77 } 78 } 79 int main() 80 { 81 int sx,sy; 82 int lx,ly; 83 for(int i=1;i<=100;i++) 84 for(int j=1;j<=100;j++) 85 ans[i][j]=1234567; //這一步賦值很關鍵!之前用memset賦0x7f,會錯一個點 86 n=read(); 87 for(int i=1;i<=n;i++) 88 for(int j=1;j<=n;j++) 89 { 90 cin>>a[i][j]; 91 if(a[i][j]=='A') 92 { 93 sx=i; 94 sy=j; 95 ans[i][j]=-1; 96 } 97 if(a[i][j]=='B') 98 { 99 lx=i; 100 ly=j; 101 } 102 } 103 dfs(sx,sy); 104 if(ans[lx][ly]==1234567) 105 { 106 cout<<-1<<endl; 107 return 0; 108 } 109 cout<<ans[lx][ly]<<endl; 110 return 0; 111 }