校园迷宫-rqnoj-195

和上面的八数码难题差不多,因为是求最优解,所以用队列,至于判重,把一个个坐标映射成一个整数。


#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=2000+10;
int a[maxn][maxn];
int n,m;

struct state
{
    int x,y;
    int step;
};

state start,target;

queue<state> q;
map <int,int> hash;


void init()
{
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
}

int gethash(state st)
{
    return st.x*m+st.y;
}

void readdata()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++)
        for (int j=1;j<=m;j++)
            scanf("%d",&a[i][j]);
            
//    printmap();
    scanf("%d%d",&start.x,&start.y);
    scanf("%d%d",&target.x,&target.y);
    start.step=0;
    q.push(start);
    hash[gethash(start)]=1;
}

bool trytoinsert(state st)
{
    int h=gethash(st);
    if (hash[h]) return false;
    hash[h]=1;
    return true;
}

void check(state st)
{
    if (gethash(st)==gethash(target))
    {
        printf("%d\n",st.step);
        exit(0);
    }
}

int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
void expand(state cur, state &st,int i)
{
    memcpy(&st,&cur,sizeof(cur));
    st.x+=dx[i];
    st.y+=dy[i];
    st.step++;
}

void work()
{
    while (!q.empty())
    {
        state cur=q.front();
        q.pop();
        //printf("%d,%d,%d\n",cur.x,cur.y,cur.step);
        for (int i=0;i<4;i++)
        {
            state st;
            expand(cur,st,i);
            if (a[st.x][st.y] || st.x<1 ||st.x>n ||st.y<1 || st.y>m) continue;
            check(st);
            if (trytoinsert(st)) q.push(st);
        }
    }
    printf("No Answer!\n");
}

int main()
{
    //init();
    readdata();
    work();
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值