1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include<iostream> #include<cstring> #include<algorithm> #include<queue> #define x first #define y second using namespace std;
const int N = 110;
int map[N][N], st[N][N], dist[N][N]; int n,m; int dx[] = {0,1,0,-1}, dy[] = {1,0,-1,0};
int main() { cin >> n >> m; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) cin >> map[i][j]; memset(dist, -1, sizeof dist); queue<pair<int,int>> q; q.push({0,0}); dist[0][0] = 0; while(q.size()) { int x = q.front().x; int y = q.front().y; q.pop(); int t = dist[x][y]; for(int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if(nx >= 0 && nx < n && ny >= 0 && ny < m && map[nx][ny] == 0 && dist[nx][ny] == -1) { q.push({nx,ny}); dist[nx][ny] = t + 1; } } } cout << dist[n - 1][m - 1]; return 0; }
|