题解 | #走迷宫#
走迷宫
https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64
#include <iostream> #include<queue> #include<cstring> #include<algorithm> using namespace std; typedef pair<int, int> PII; const int N = 1010; char g[N][N]; int d[N][N]; int x1, y1, x2, y2; int n, m; int bfs(){ queue<PII> q; memset(d, -1, sizeof d); d[x1][y1] = 0; q.push({x1, y1}); int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; while(q.size()){ auto t = q.front(); q.pop(); for(int i = 0; i < 4; i ++){ int x = t.first + dx[i], y = t.second + dy[i]; if(x < n && y < m && x >= 0 && y >= 0 && g[x][y] == '.' && d[x][y] == -1){ d[x][y] = d[t.first][t.second] + 1; q.push({x, y}); } } } return d[x2][y2]; } int main() { cin >> n >> m; cin >> x1 >> y1 >> x2 >> y2; x1 --, y1 --, x2 --, y2 --; for(int i = 0; i < n; i ++) for(int j = 0; j < m; j ++) cin >> g[i][j]; cout << bfs() << endl; return 0; }