原题跳转
这是一道bfs的题。标记出不能走的方格,一点一点往下递归,每次更新答案(时间)即可。 需要注意的地方已经在代码中标出。
参考代码
#include <iostream>
#include <queue>
using namespace std;
struct node {
int x,y,tm;
};
int dx[8]={1,0,-1,0,1,1,-1,-1},dy[8]={0,1,0,-1,-1,1,1,-1};//8个坐标提前预设好,bfs方便往前推
int ans;
char a[105][105];
queue<node> myq;
void bfs(){
while (!myq.empty()){//没有推到边界就继续推
node t = myq.front();
myq.pop();
ans = t.tm;
for (int i = 0; i < 8; i++) {//8个方向进行枚举
int x = t.x + dx[i];
int y = t.y + dy[i];
if (a[x][y] == '.') {
a[x][y] = '*';
myq.push({x,y,t.tm+1});//如果符合条件,就把下一层的数据压进队列
}
}
}
}
int main() {
int n,m,sx,sy;
cin>>m>>n>>sy>>sx;//注意先输入列,后输入行
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++)
cin >> a[i][j];
}
myq.push({n-sx+1,sy,0});//(1,1)定义为左下角,所以x轴坐标要用(n-sx+1)
a[n-sx+1][sy]='*';
bfs();
cout<<ans<<endl;
return 0;
}