逃离迷宫
Time Limit : 1000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 230 Accepted Submission(s) : 68
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Input
第1行为两个整数m, n (1 ≤ m, n ≤ 100),分别表示迷宫的行数和列数,接下来m行,每行包括n个字符,其中字符'.'表示该位置为空地,字符'*'表示该位置为障碍,输入数据中只有这两种字符,每组测试数据的最后一行为5个整数k, x 1, y 1, x 2, y 2 (1 ≤ k ≤ 10, 1 ≤ x 1, x 2 ≤ n, 1 ≤ y 1, y 2 ≤ m),其中k表示gloria最多能转的弯数,(x 1, y 1), (x 2, y 2)表示两个位置,其中x 1,x 2对应列,y 1, y 2对应行。
Output
Sample Input
2 5 5 ...** *.**. ..... ..... *.... 1 1 1 1 3 5 5 ...** *.**. ..... ..... *.... 2 1 1 1 3
Sample Output
noyes
#include<iostream> #include<cstdio> #include<algorithm> #include<string.h> char a[101][101]; bool bb; int step[101][101]; int m, n, k, x1, y11, x2, y2, d[4][2] = { {1,0},{0,-1},{-1,0},{0,1} }; using namespace std; int main() { void dfs(int, int, int,int); int T; scanf("%d", &T); while (T--) { bb = 0; scanf("%d%d", &m, &n); for (int i = 0; i < m; i++) scanf("%s",&a[i]); for(int i=0; i<m; i++) for(int j=0; j<n; j++) step[i][j]=99999999; scanf("%d%d%d%d%d", &k, &y11, &x1, &y2, &x2); y11--, x1--, x2--, y2--; a[x1][y11]='#'; step[x1][y11]=0; dfs(x1, y11, -1, 0); if (bb == 0) printf("no\n"); } return 0; } void dfs(int x, int y, int de, int st) { if (st > k) return; if (bb == 1) return; if (st == k) { if (x != x2&&y != y2) return; if (de == 0 && y != y2) return; if (de == 1 && x != x2) return; } if (x == x2&&y == y2) { printf("yes\n"); bb = 1; return; } for (int i = 0; i < 4; i++) { int xx = x + d[i][0], yy = y + d[i][1]; if (xx >=0 && xx<m&&yy >=0 && yy<n&&a[xx][yy] == '.') { if(step[xx][yy]<step[x][y]) { continue; } a[xx][yy]='#'; if (de == -1) { step[xx][yy]=step[x][y]; dfs(xx, yy, i % 2, st); } else if (de == i % 2) { step[xx][yy]=step[x][y]; dfs(xx, yy, de, st); } else { step[xx][yy]=step[x][y]+1; dfs(xx, yy, i % 2, st + 1); } if (bb == 1) return; a[xx][yy]='.'; } } }
一开始用memset初始化,结果wa了,用step数组保存到每一步时的转折次数,如果另一条搜索路径到此点时step更大,则停止搜索