样例输入
4 3 1 1
....
..*.
.**.
样例输出
4
题解
一定注意 u,vu,v 的位置处理。
这道题目想必你已经可以直接想到bfs搜索了吧。把整个图遍历一遍,顺便记录下步数就可以了。
其他的就是和普通bfs差不太多。
#include<bits/stdc++.h>
using namespace std;
int X,Y,mx,my;
char mp[105][105];
int ans;
int dir[8][2]={{0,1},{1,1},{1,0},{0,-1},{-1,-1},{-1,0},{-1,1},{1,-1}};
struct Node{
int x,y;
int d;
};
void bfs(int xx,int yy){
queue<Node> q;
q.push({xx,yy,0});
while(!q.empty()){
Node now=q.front();
ans=now.d;
q.pop();
for(int i=0;i<8;i++){
int tx=now.x+dir[i][0];
int ty=now.y+dir[i][1];
if(mp[tx][ty]=='.'&&tx>=0&&tx<Y&&ty>=0&&ty<=X){
mp[tx][ty]='M';
q.push({tx,ty,now.d+1});
}
}
}
}
int main(){
cin>>X>>Y>>mx>>my;
int tx=Y-my;
int ty=mx-1;
mx=tx,my=ty;
for(int i=0;i<Y;i++){
cin>>mp[i];
}
mp[mx][my]='M';
bfs(mx,my);
cout<<ans<<endl;
return 0;
}