#include<bits/stdc++.h> using namespace std; char a[41][41]; int r, c; int f[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // 四个方向; struct Node //路径上的点,x,y为该点坐标,step为从起点到达该点所需的频数 { int x, y, step; }; int bfs(int x, int y) { a[x][y] = '#'; queue<Node> q; q.push({x, y, 1}); while (!q.empty()) { Node node = q.front(); q.pop(); if (node.x == r && node.y == c) return node.step;// 到达终点 for (int i = 0; i < 4; ++i) // 遍历四个方向 { int tx = node.x + f[i][0]; int ty = node.y + f[i][1]; if (tx < 1 || tx > r || ty < 1 || ty >c || a[tx][ty] == '#') continue; a[tx][ty] = '#'; q.push({tx, ty, node.step + 1}); } } return -1; } int main() { cin >> r >> c; for (int i = 1; i <= r; i++) for (int j = 1; j <= c; j++) cin >> a[i][j]; cout << bfs(1, 1); return 0; } /************************************************************** Problem: 1432 User: wf9000 Language: C++ Result: Accepted Time:26 ms Memory:2080 kb ****************************************************************/