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
| 1 const int INF = 100000000; 2 3 4 typedef pair<int, int> P; 5 6 7 char maze[MAX_N][MAX_M + 1]; 8 int N, M; 9 int sx, sy; 10 int gx, gy; 11 12 int d[MAX_N][MAX_M]; 13 14 15 int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; 16 17 18 19 int bfs() { 20 queue<P> que; 21 22 for (int i = 0; i < N; i++) 23 for (int j = 0; j < M; j++) d[i][j] = INF; 24 25 que.push(P(sx, sy)); 26 d[sx][sy] = 0; 27 28 29 while (que.size()) { 30 31 P p = que.front(); que.pop(); 32 33 if (p.first == gx && p.second == gy) break; 34 35 36 for (int i = 0; i < 4; i++) { 37 38 int nx = p.first + dx[i], ny = p.second + dy[i]; 39 40 41 if (0 <= nx && nx < N && 0 < ny && ny < M && maze[nx][ny] != '#' && d[nx][ny] == INF) { 42 43 que.push(P(nx, ny)); 44 d[nx][ny] = d[p.first][p.second] + 1; 45 } 46 } 47 } 48 return d[gx][gy]; 49 } 50 51 void solve() { 52 int res = bfs(); 53 printf("%d\n", res); 54 }
|