hash(good)codeforces225D

本文介绍了一种解决经典Snake游戏问题的方法,通过哈希和广度优先搜索(BFS)算法来寻找蛇吃到苹果所需的最少移动次数。文章提供了一个完整的C++实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

D. Snake
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Let us remind you the rules of a very popular game called "Snake" (or sometimes "Boa", "Python" or "Worm").

The game field is represented by an n × m rectangular table. Some squares of the field are considered impassable (walls), all other squares of the fields are passable.

You control a snake, the snake consists of segments. Each segment takes up exactly one passable square of the field, but any passable square contains at most one segment. All segments are indexed by integers from 1 to k, where k is the snake's length. The 1-th segment is the head and the k-th segment is the tail. For any i (1 ≤ i < k), segments with indexes i and i + 1 are located in the adjacent squares of the field, that is, these squares share a common side.

One of the passable field squares contains an apple. The snake's aim is to reach the apple and eat it (that is, to position its head in the square with the apple).

The snake moves throughout the game. During one move the snake can move its head to an adjacent field square. All other segments follow the head. That is, each segment number i (1 < i ≤ k) moves to the square that has just had segment number i - 1. Consider that all segments including the head move simultaneously (see the second test sample). If the snake's head moves to an unpassable square or to the square, occupied by its other segment, the snake dies. That's why we will consider such moves unvalid.

Your task is to determine the minimum number of valid moves that the snake needs to reach the apple.

Input

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 15) — the number of rows and columns of the game field.

Next n lines describe the game field. Each of these lines contains m characters. Character "#" represents a wall, "." is a passable square, "@" is an apple. The snake's first segment is represented by character "1", the second one segment — by character "2" and so on.

The game field description doesn't contain any characters besides "#', ".", "@" and digits (except 0). It is guaranteed that the described field is correct. It is guaranteed that the described field contains exactly one apple and exactly one snake, the snake's length is at least 3 and at most 9.

Output

Print a single integer to the output — the minimum number of moves needed to reach the apple. If the snake can't reach the apple, print -1.

Sample test(s)
Input
4 5
##...
..1#@
432#.
...#.
Output
4
Input
4 4
#78#
.612
.543
..@.
Output
6
Input
3 2
3@
2#
1#
Output
-1



对蛇进行hash,然后bfs就可以了

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=20;
char g[maxn][maxn];
int ax,ay,sx,sy;
int N,M,len;
bool vis[20000010];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct node
{
    int x[10],y[10];
    int step;
    node(){step=0;}
};
int find(node a,int i)
{
    for(int j=0;j<4;j++)
    {
        int x=a.x[i-1]+dx[j];
        int y=a.y[i-1]+dy[j];
        if(x==a.x[i]&&y==a.y[i])return j;
    }
}
int gethash(int sx,int sy,node a)
{
    int hash=sx*M+sy;
    for(int i=1;i<len;i++)
        hash=hash*4+find(a,i);
    return hash;
}

void solve(node s)
{
    queue<node> q;
    s.step=0;
    q.push(s);
    while(!q.empty())
    {
        node a=q.front();q.pop();
        for(int i=0;i<4;i++)
        {
            int x=a.x[0]+dx[i];
            int y=a.y[0]+dy[i];
            if(x<1||x>N||y<1||y>M||g[x][y]=='#')continue;
            bool flag=true;
            for(int j=1;j<len-1;j++)
                if(x==a.x[j]&&y==a.y[j])
                    {flag=false;break;}
            if(!flag)continue;
            node tmp;
            tmp.x[0]=x,tmp.y[0]=y;
            for(int j=1;j<len;j++)
            {
                tmp.x[j]=a.x[j-1];
                tmp.y[j]=a.y[j-1];
            }
            int hash=gethash(x,y,tmp);
            if(!vis[hash])
            {
                tmp.step=a.step+1;
                vis[hash]=1;
                q.push(tmp);
            }
            if(x==ax&&y==ay){printf("%d\n",tmp.step);return;}
        }
    }
    printf("-1\n");
}
int main()
{
    scanf("%d%d",&N,&M);
    node s;
    for(int i=1;i<=N;i++)
    {
        scanf("%s",g[i]+1);
        for(int j=1;j<=M;j++)
        {
            if(g[i][j]=='@')ax=i,ay=j;
            else if(g[i][j]>='1'&&g[i][j]<='9')
            {
                if(g[i][j]=='1')sx=i,sy=j;
                s.x[g[i][j]-'1']=i;
                s.y[g[i][j]-'1']=j;
                len++;
                g[i][j]='.';
            }
        }
    }
    int tmp=gethash(sx,sy,s);
    vis[tmp]=1;
    solve(s);
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值