题解
2024-12-07 19:59:27
发布于:广东
32阅读
0回复
0点赞
这题也能用广搜,具体我就不多讲了。
代码如下:
#include<bits/stdc++.h>
using namespace std;
char a[3005][3005];
int dx[4] = {1,-1,0,0},dy[4] = {0,0,1,-1};
bool vis[3005][3005];
struct node{
int x,y,step;
};
int main(){
int n,m;
cin >> n >> m;
for(int i = 0;i < n;i ++){
for(int j = 0;j < m;j ++){
cin >> a[i][j];
}
}
queue<node> q;
q.push({0,0,0});
while(!q.empty()){
int ix = q.front().x,iy = q.front().y,istep = q.front().step;
q.pop();
if(ix == n - 1 and iy == m - 1){
cout << istep;
return 0;
}
for(int i = 0;i < 4;i ++){
int nx = ix,ny = iy;
while(a[nx + dx[i]][ny + dy[i]] == '*' and nx + dx[i] >= 0 and ny + dy[i] >= 0 and nx + dx[i] < n and ny + dy[i] < m){
nx += dx[i];
ny += dy[i];
}
if((nx != ix or ny != iy) and vis[nx][ny] == 0){
vis[nx][ny] = 1;
q.push({nx,ny,istep + 1});
}
nx = ix + dx[i],ny = iy + dy[i];
if(a[nx][ny] != '#' and nx >= 0 and ny >= 0 and nx < n and ny < m and vis[nx][ny] == 0){
vis[nx][ny] = 1;
q.push({nx,ny,istep + 1});
}
}
}
cout << -1;
return 0;
}
这里空空如也
有帮助,赞一个