AcWing 188. 武士风度的牛
考察:bfs
思路:
行走方式不同的迷宫问题,最坑的是输入的先是列数再是行数.
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 const int N = 160; 7 typedef pair<int,int> PII; 8 char mp[N][N]; 9 int n,m,d[N][N]; 10 const int xx[8]= {2,1,-1,-2,-2,-1, 1, 2}; 11 const int yy[8]= {1,2,2 ,1, -1,-2,-2,-1}; 12 int bfs(int x,int y) 13 { 14 memset(d,-1,sizeof d); 15 queue<PII> q; 16 q.push({x,y}); 17 d[x][y] = 0; 18 while(q.size()) 19 { 20 auto it = q.front(); 21 q.pop(); 22 int nx = it.first,ny = it.second; 23 if(mp[nx][ny]=='H') return d[nx][ny]; 24 for(int i=0;i<8;i++) 25 { 26 int dx = nx+xx[i],dy = ny+yy[i]; 27 if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&mp[dx][dy]!='*'&&d[dx][dy]==-1) 28 { 29 d[dx][dy] = d[nx][ny]+1; 30 q.push({dx,dy}); 31 } 32 } 33 } 34 return -1; 35 } 36 int main() 37 { 38 scanf("%d%d",&m,&n); 39 for(int i=1;i<=n;i++) 40 scanf("%s",mp[i]+1); 41 for(int i=1;i<=n;i++) 42 for(int j=1;j<=m;j++) 43 if(mp[i][j]=='K') 44 { 45 printf("%d\n",bfs(i,j)); 46 return 0; 47 } 48 return 0; 49 }