HDJ 1728(逃离迷宫)

/* BFS中等题
Date: 2012/10/4
思路:一个方向,一个方向的找,visited[i][j],表示从起始点到i,j转弯的次数
*/
#include<iostream>
#include<queue>
using namespace std;
#define maxn 105
char maze[maxn][maxn];
int dir[][2] = {{0,-1},{1,0},{0,1},{-1,0}};
int visited[maxn][maxn];
int m,n,k,si,sj,ei,ej;
bool ok(int i,int j)
{
    if(i >= 0 && i < m && j >= 0 && j < n && maze[i][j] != '*')
        return true;
    return false;
}
struct node
{
    int x,y;
};
void BFS()
{
    queue<node> q;
    memset(visited,-1,sizeof(visited));
    node temp,next;
    temp.x = si,temp.y = sj;
    q.push(temp);
    while(!q.empty())
    {
        temp = q.front();
        q.pop();
        int times = visited[temp.x][temp.y]+1;  //之前找到temp的方向的点都已被找过,所以接下来的方向与之前找到temp的方向不同,所以拐弯了,需+1
        for(int i = 0; i < 4; i++)
        {
            next.x = temp.x+dir[i][0],next.y = temp.y+dir[i][1];
            while(ok(next.x,next.y))
            {
                if(visited[next.x][next.y] == -1)   //此点从没被找过
                {
                    if(next.x == ei && next.y == ej && times <= k)
                    {
                        printf("yes\n");
                        return;
                    }
                    q.push(next),visited[next.x][next.y] = times;
                }
                next.x += dir[i][0],next.y += dir[i][1];
            }
        }
    }
    printf("no\n");
}
int main()
{
    //freopen("1010.txt","r",stdin);
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int i,j;
        scanf("%d%d",&m,&n);
        for(i = 0; i < m; i++)
            for(j = 0; j < n; j++)
                cin >> maze[i][j];
            //scanf("%s",maze[i]);
        scanf("%d%d%d%d%d",&k,&sj,&si,&ej,&ei);
        si--,sj--,ei--,ej--;
        BFS();
    }
    return 0;
}

 

posted @ 2012-10-04 16:12  sorryhao  阅读(253)  评论(0)    收藏  举报