2024-01-21 15:16:13
发布于:广东
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
struct Point{
int x, y, step;
};
int n, m;
bool vis[45][45];
char mp[45][45];
int dir[4][2] = {-1, 0, 0, -1, 0, 1, 1, 0};
queue <Point> q;
bool check(int x, int y){
if(x < 1 || x > n) return 0;
if(y < 1 || y > m) return 0;
if(mp[x][y] != '.') return 0;
if(vis[x][y]) return 0;
return 1;
}
void bfs(int x, int y){
vis[x][y] = 1;
q.push({x, y, 0});
while(!q.empty()){
Point head = q.front();
if(head.x == n && head.y == m){
cout << head.step;
return;
}
for(int i = 0; i < 4; i++){
int xx = head.x + dir[i][0], yy = head.y + dir[i][1];
if(check(xx, yy)){
q.push({xx, yy, head.step + 1});
vis[xx][yy] = 1;
}
}q.pop();
}cout << -1;
}
int main(){
freopen("guangsou.in", "r", stdin);
freopen("guangsou.out", "w", stdout);
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> mp[i][j];
}
}bfs(1, 1);
fclose(stdin), fclose(stdout);
return 0;
}
这里空空如也
有帮助,赞一个