标签:des style blog java color strong
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 14376 Accepted Submission(s): 3458
一开始自己搜DFS题,搜到了这一题,然后好不容易做出来,居然超时了,优化剪枝还是超时,但网上只看到一个用DFS做的,思路基本差不多,就有一个判断拐弯的次数有点不一样,后面就上网看了一下别人写的BFS。
解题思路:就是用BFS不断的往一个方向搜,而不是往它上下左右去搜,到了搜不了的地方就返回吧。
贴出代码:
#include <stdio.h> #include <queue> using namespace std; char map[105][105]; int visited[105][105], mark; int dir[4][2]={-1, 0, 0, 1, 1, 0, 0, -1}; struct node { int x, y; int Dir, num; }; int Judge(int n, int m, int x, int y) { if(x>=1 && x<=m && y>=1 && y<=n && map[x][y] == ‘.‘) return 1; else return 0; } void BFS(int k, int x1, int y1, int x2, int y2, int n, int m) { struct node Node, temp; queue <node> Q; Node.x = x1; Node.y = y1; Node.num = -1; visited[x1][y1] = 1; Q.push(Node); while(!Q.empty()) { temp = Q.front(); Q.pop(); if(temp.num >= k) continue; for(int i = 0; i<4; i++) { Node = temp; Node.x += dir[i][1]; Node.y += dir[i][0]; Node.num++; while(Judge(n, m, Node.x, Node.y)) { if(Node.x == x2 && Node.y == y2) { mark = 1; return; } if(!visited[Node.x][Node.y]) { visited[Node.x][Node.y] = 1; Q.push(Node); } Node.x += dir[i][1]; Node.y += dir[i][0]; } } } } int main() { int m, n, T; int k, x1, y1, x2, y2; scanf("%d", &T); while(T--) { mark = 0; scanf("%d%d", &m, &n); for(int i = 1; i<=m; i++) { getchar(); for(int j = 1; j<=n; j++) { scanf("%c", &map[i][j]); visited[i][j] = 0; } } scanf("%d%d%d%d%d", &k, &y1, &x1, &y2, &x2); BFS(k, x1, y1, x2, y2, n, m); if(mark) printf("yes\n"); else printf("no\n"); } return 0; }
hdu 1728 逃离迷宫 (BFS),布布扣,bubuko.com
标签:des style blog java color strong
原文地址:http://www.cnblogs.com/fengxmx/p/3849223.html