【搜索】 HDU 3137 No Left Turns

题意:S到F 只能直走和右拐

求最少步数

开始可以任意选择一个方向


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <cmath>
using namespace std;
#include <queue>
#include <stack>
#include <vector>
#include <deque>
#include <map>
#define cler(arr, val)    memset(arr, val, sizeof(arr))
typedef long long  LL;
const int MAXN = 543;
const int MAXM = 260110;
const int INF = 0x3f3f3f3f;
const int mod = 1000000007;
char mp[21][21];
bool vis[4][21][21];
int n,m;
struct node
{
    int fx;
    int x,y,step;
};
queue<node>q;
bool ok(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m&&mp[x][y]!='X') return true;
    return false;
}
int bfs(int x,int y)
{
    cler(vis,false);
    while(!q.empty()) q.pop();
    node front,rear;
    front.x=x,front.y=y;
    front.step=0;
    for(int i=0;i<4;i++)
    {
        front.fx=i;
        q.push(front);
        vis[i][x][y]=true;
    }
    while(!q.empty())
    {
        front=q.front();
        q.pop();
        int dx1=front.x,dy1=front.y,fx;
        int dx2=front.x,dy2=front.y;
        if(front.fx==0) dx1-=1,dy2+=1,fx=3;//上
        if(front.fx==1) dx1+=1,dy2-=1,fx=2;//下
        if(front.fx==2) dy1-=1,dx2-=1,fx=0;//左
        if(front.fx==3) dy1+=1,dx2+=1,fx=1;//右
        if(ok(dx1,dy1)&&!vis[front.fx][dx1][dy1])
        {
            if(mp[dx1][dy1]=='F')
                return front.step+1;
            vis[front.fx][dx1][dy1]=true;
            rear.x=dx1,rear.y=dy1,rear.fx=front.fx,rear.step=front.step+1;
            q.push(rear);
        }
        if(ok(dx2,dy2)&&!vis[fx][dx2][dy2])
        {
            if(mp[dx2][dy2]=='F')
                return front.step+1;
            vis[fx][dx2][dy2]=true;
            rear.x=dx2,rear.y=dy2,rear.fx=fx,rear.step=front.step+1;
            q.push(rear);
        }
    }
}
void init()
{

    cin>>n>>m;
    getchar();
    for(int i=0; i<n; i++)
        gets(mp[i]);
    for(int i=0; i<n; i++)
        for(int j=0; j<m; j++)
            if(mp[i][j]=='S')
            {
                printf("%d\n",bfs(i,j));
                return ;
            }
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    int t;
    scanf("%d",&t);
    while(t--)
    {
        init();
    }
    return 0;
}


posted @ 2014-11-05 19:15  kewowlo  阅读(132)  评论(0编辑  收藏  举报