魔鬼之城

题目描述

在一个被分割为N*M个正方形房间的矩形魔鬼之城中,一个探险者必须遵循下列规则才能跳跃行动。他必须从(1, 1)进入,从(N, M)走出;在每一房间的墙壁上都写了一个魔法数字,是1~13之内的自然数;探险者可以想像出8个方向中的任何一个(水平或垂直或对角线方向),随后他就可以作一次空间跳跃穿过这一方向上的连续的X个房间,其中X是他原来所在房间的魔法数字。但如果在这一方向上的房间数小于X,则他不作任何跳跃,而必须想像另一个方向。同时,探险者不能作连续两次相同方向的跳跃。

例如在上图的5*4的魔鬼之城中,如果探险者现在所在的位置是(3, 3),那么通过依次空间跳跃他可以到达下列房间中的一个:(1, 1),(3, 1),(1, 3),(5, 1),或(5, 3)。另外,如果他要用两次跳跃从(5, 4)到达(3, 2),则他不能首先跳到(4, 3)(因为这样他第二次跳跃的方向将和第一次相同,而这是不允许的)。所以他必须先跳跃到(2, 1)。

请你写一个程序,对给定的地图,算出探险者至少需要跳跃多少步才能离开魔鬼之城。

输入格式

一行给出N,M(都不超过100);

下来有M行,每行为N个自然数,表示对应房间中的魔法数字。

输出格式

出最小步数,如果探险者无法离开魔鬼之城,请输出“NEVER”。

输入输出样例

输入 #1
5 4
3 3 6 7 11
3 2 1 1 3
3 2 2 1 1
2 1 2 2 1
输出 #1
4

分析:
一道简单的BFS???(大雾)对于每个位置直接BFS就完事了,只要注意一下判断该点从每个方向是否来过即可。

CODE:
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int M=105;
const int xcor[10]={0,1,0,-1,1,-1,-1,1};
const int ycor[10]={1,0,-1,0,1,-1,1,-1};
bool vis[M][M][10];
int n,m,ans=1<<20;
int a[M][M];
struct node{
    int xnow,ynow,tot,last;
};
int get(){
    int res=0,f=1;
    char c=getchar();
    while (c>'9'||c<'0') {
        if (c=='-') f=-1;
        c=getchar();
    }
    while (c<='9'&&c>='0'){
        res=(res<<3)+(res<<1)+c-'0';
        c=getchar();
    }
    return res*f;
}
queue<node> q;
void bfs(){
    q.push((node){1,1,0,-1});
    while (!q.empty()){
        node x=q.front();
        q.pop();
        //cout<<x.xnow<<" "<<x.ynow<<" "<<x.tot<<" "<<x.last<<endl; 
        if (x.xnow==m&&x.ynow==n) ans=min(ans,x.tot);
        //cout<<ans<<endl;
        for (int i=0;i<=7;i++){
            if (x.last==i) continue;
            int lastx=x.xnow+xcor[i]*a[x.xnow][x.ynow];
            int lasty=x.ynow+ycor[i]*a[x.xnow][x.ynow];
            if (lastx>m||lastx<1) continue;
            if (lasty>n||lasty<1) continue;
            if (vis[lastx][lasty][i]) continue;
            q.push((node){lastx,lasty,x.tot+1,i});
            vis[lastx][lasty][i]=true;
        }
    }
    return ;
}
int main(){
    n=get(),m=get();//n是列,m是行 
    for (int i=1;i<=m;i++)
        for (int j=1;j<=n;j++)
            a[i][j]=get();
    bfs();
    if (ans==1<<20) printf ("NEVER
"); 
    else printf ("%d
",ans);
    return 0;
}


 
原文地址:https://www.cnblogs.com/kanchuang/p/11503053.html