leetcode 773. 滑动谜题(模板bfs)

10 篇文章 0 订阅

题目
在这里插入图片描述在这里插入图片描述
好像可以双搜?晚上再补。。
我好烦啊,图书馆旁边那女的为什么画图要啪啪的放笔啊,无语。全世界都要听到它的笔1s掉下来一次。

class Solution {
typedef pair<int,int> pi;
public:
    int p[6]={1,10,100,1000,10000,100000};
    int hash(vector<vector<int>>& board){
        return board[0][0]+board[0][1]*10+board[0][2]*100+board[1][0]*1000+board[1][1]*10000+board[1][2]*100000;
    }
    int vis[543211],a[6],ans=54321;
    int slidingPuzzle(vector<vector<int>>& board) {
        queue<pi>q;
        q.push({hash(board),0}),vis[hash(board)]=1;
        while(!q.empty()){
            pi cur=q.front();q.pop();
            int x=cur.first,y=cur.second,dex;
            if(x==ans) return y;
            for(int i=0;i<6;++i){
                a[i]=x%10,x/=10;
                if(!a[i]) dex=i;
            }
            //上
            if(dex>=3){
                int rehash=cur.first+a[dex-3]*(p[dex]-p[dex-3]);
                if(!vis[rehash]) q.push({rehash,y+1}),vis[rehash]=1;
            }
            //下
            if(dex<3){
                int rehash=cur.first+a[dex+3]*(p[dex]-p[dex+3]);
                if(!vis[rehash]) q.push({rehash,y+1}),vis[rehash]=1;
            }
            //左
            if(dex!=0&&dex!=3){
                int rehash=cur.first+a[dex-1]*(p[dex]-p[dex-1]);
                if(!vis[rehash]) q.push({rehash,y+1}),vis[rehash]=1;
            }
            //右
            if(dex!=2&&dex!=5){
                int rehash=cur.first+a[dex+1]*(p[dex]-p[dex+1]);
                if(!vis[rehash]) q.push({rehash,y+1}),vis[rehash]=1;
            }
        }
        return -1;
    }
};

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值