Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8505 | Accepted: 3728 |
Description
Input
Output
Sample Input
2 8 8 ######## #......# #.####.# #.####.# #.####.# #.####.# #...#..# #S#E#### 9 5 ######### #.#.#.#.# S.......E #.#.#.#.# #########
Sample Output
37 5 5 17 17 9
思路:
题不难,但同时考到了深搜+广搜;
需要注意,往左优先的深搜和往右优先的深搜搜出来的最小步数不一定是整体的最小步数;求最小步数,必须广搜!
代码:
#include <stdio.h> #include <string.h> #include <queue> #define N 45 using namespace std; struct Node{ int x; int y; int s; int fx; }; char map[N][N]; bool bz[N][N]; int m, n; queue<Node>q; int fx[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; int f[4][4][2] = { {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}, {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}, {{1, 0}, {-1, 0}, {0, -1}, {0, 1}}, {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}, }; int bfs(); int dfs(Node start, int fxi); void getfx(Node &cur); int main() { int k; scanf("%d", &k); while(k --){ while(!q.empty()) q.pop(); memset(map, '#', sizeof(map)); memset(bz, 0, sizeof(bz)); scanf("%d%d", &m, &n); Node start; for(int i = 1; i <= n; i ++){ for(int j = 1; j <= m; j ++){ scanf(" %c", &map[i][j]); if(map[i][j] == 'S'){ start.x = i; start.y = j; start.s = 1; q.push(start); map[i][j] = '#'; } } } getfx(start); int minl = dfs(start, 0); int minr = dfs(start, 1); int mins = bfs(); printf("%d %d %d\n", minl, minr, mins); } return 0; } int bfs() { Node cur; while(1){ cur.x = q.front().x; cur.y = q.front().y; cur.s = q.front().s + 1; q.pop(); for(int i = 0; i < 4; i ++){ Node nw = cur; nw.x += fx[i][0]; nw.y += fx[i][1]; if(map[nw.x][nw.y] == '#' || bz[nw.x][nw.y]) continue; if(map[nw.x][nw.y] == 'E') return nw.s; bz[nw.x][nw.y] = 1; q.push(nw); } if(q.empty()) return -1; } } int dfs(Node cur, int fxi) { Node nw; int i = cur.fx; int ok; int x = cur.x + f[i][fxi][0]; int y = cur.y + f[i][fxi][1]; char c = map[x][y]; if(c == 'E'){ // fxi 方向 return cur.s + 1; } else if(c == '.'){ nw.x = x; nw.y = y; nw.s = cur.s + 1; if(fxi == 0) nw.fx = (cur.fx + 3) % 4; else nw.fx = (cur.fx + 1) % 4; ok = dfs(nw, fxi); if(ok) return ok; } else{ x = cur.x + f[i][2][0]; y = cur.y + f[i][2][1]; c = map[x][y]; if(c == 'E'){ // cur.fx 方向 return cur.s + 1; } else if(c == '.'){ nw.x = x; nw.y = y; nw.s = cur.s + 1; nw.fx = cur.fx; ok = dfs(nw, fxi); if(ok) return ok; } else{ int nfx = (fxi + 1) % 2; x = cur.x + f[i][nfx][0]; y = cur.y + f[i][nfx][1]; c = map[x][y]; if(c == 'E'){ // - fxi 方向 return cur.s + 1; } else if(c == '.'){ nw.x = x; nw.y = y; nw.s = cur.s + 1; if(nfx == 0) nw.fx = (cur.fx + 3) % 4; else nw.fx = (cur.fx + 1) % 4; ok = dfs(nw, fxi); if(ok) return ok; } else{ // -cur.fx 方向 nw.x = cur.x + f[i][3][0]; nw.y = cur.y + f[i][3][1]; nw.s = cur.s + 1; nw.fx = (cur.fx + 2) % 4; ok = dfs(nw, fxi); if(ok) return ok; } } } return 0; } void getfx(Node &cur) { if(cur.x == 1) cur.fx = 1; if(cur.x == n) cur.fx = 3; if(cur.y == 1) cur.fx = 0; if(cur.y == n) cur.fx = 2; }