题目链接:Children of the Candy Corn
解题思路:这道是DFS BFS的混合题目,记录好当前的位置信息,在根据左优先(左前右后)右优先(右前左后)的方式走完整个迷宫。最后的最短路径就用BFS解决就好了。
#include<stdio.h> #include<string.h> #include<queue> #define MAX 45 using namespace std; struct A{ int x, y, time; }; typedef struct A node; char map[MAX][MAX]; int v[MAX][MAX]; const int dir[4][2] = {-1,0,0,1,1,0,0,-1}; int pri[2][4] = {3,0,1,2,1,0,3,2}; int n, m, ans, pos; int sx, sy, ex, ey; int judge(int x, int y){ if(x <= 0 || y <= 0 || x > n || y > m){ return 0; } return 1; } void DFS(int x, int y, int head, int priority, int depth){ int i, j; if(ans != -1){ return; } if(x == ex && ey == y){ ans = depth; } for(i = 0; i < 4; i++){ int d = (head + pri[priority][i]) % 4; int temx = x + dir[d][0]; int temy = y + dir[d][1]; if(judge(temx, temy) && map[temx][temy] != '#'){ DFS(temx, temy, d, priority, depth + 1); } } } int BFS(){ queue<node> my; node s, tem; int i, j; tem.x = sx;tem.y = sy;tem.time = 1; my.push(tem); v[sx][sy] = 1; while(!my.empty()){ s = my.front(); my.pop(); for(i = 0; i < 4; i++){ int x = s.x + dir[i][0]; int y = s.y + dir[i][1]; if(judge(x, y) && map[x][y] != '#' && !v[x][y]){ v[x][y] = 1; tem.x = x;tem.y = y;tem.time = s.time + 1; if(map[x][y] == 'E'){ return tem.time; } my.push(tem); } } } } int main(){ int t, i, j; //freopen("in.txt", "r", stdin); scanf("%d", &t); while(t--){ ans = pos = -1; memset(v, 0, sizeof(v)); scanf("%d%d", &m, &n); getchar(); for(i = 1; i <= n; i++){ for(j = 1; j <= m; j++){ scanf("%c", &map[i][j]); if(map[i][j] == 'S'){ sx = i;sy = j; } if(map[i][j] == 'E'){ ex = i, ey = j; } } getchar(); } for(i = 0; i < 4; i++){ int x = sx + dir[i][0]; int y = sy + dir[i][1]; if(judge(x, y) && map[x][y] == '.'){ pos = i; break; } } DFS(sx, sy, pos, 0, 1); printf("%d", ans); ans = -1; DFS(sx, sy, pos, 1, 1); printf(" %d", ans); ans = BFS(); printf(" %d\n", ans); } return 0; }