题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1728
这道题是利用了BFS中的DFS思想,从上下左右4个点扩展到了4个方向。 这是本题的重点。
代码:
#include <cstdio> #include <cstring> #include <queue> using namespace std; char s[105][105]; int n,m; int k,x1,y1,x2,y2; int flag; int v[105][105]; int dx[] = {-1,0,1,0}; int dy[] = {0,1,0,-1}; struct node{ int x,y; int cnt; }; int bfs() { queue<node> q; memset(v,0,sizeof(v)); node f,t; f.x = x1; f.y = y1; f.cnt = -1; q.push(f); while(!q.empty()) { node h = q.front(); q.pop(); if(h.x == x2 && h.y == y2 && h.cnt <= k) return 1; t.cnt = h.cnt + 1; for(int i = 0;i < 4;++i) { t.x = h.x + dx[i]; t.y = h.y + dy[i]; while(!(t.x < 1 || t.x > n || t.y < 1 || t.y > m) && s[t.x][t.y] == '.') { if(!v[t.x][t.y]) { q.push(t); v[t.x][t.y] = 1; } t.x += dx[i]; t.y += dy[i]; } } } return 0; } int main() { int _; scanf("%d",&_); while(_--) { flag = 0; scanf("%d%d",&n,&m); getchar(); for(int i = 1;i <= n;++i) { for(int j = 1;j <= m;++j) scanf("%c",&s[i][j]); getchar(); } scanf("%d%d%d%d%d",&k,&y1,&x1,&y2,&x2); if(x1 == x2 && y1 == y2) { printf("yes\n"); continue; } flag = bfs(); if(flag) printf("yes\n"); else printf("no\n"); } return 0; }