Leetcode773-滑动谜题

24 篇文章 0 订阅

BFS

思路和八数码一样,对所有状态进行暴力广搜,直到搜到目标状态或者无解为止。也可以利用A*来优化算法。

class Solution {
public:
    string ans="123450";
    int dx[4]={0,0,-1,1};
    int dy[4]={-1,1,0,0};
    int slidingPuzzle(vector<vector<int>>& board) {
        string s;
        unordered_set<string> st;
        queue<string> q;
        for(auto p:board){
            for(auto c:p){
                s+='0'+c;
            }
        }
        if(ans==s) return 0;
        int len=1;
        q.push(s);
        st.insert(s);
        while(!q.empty()){
            int sz=q.size();
            while(sz--){
                s=q.front();
                q.pop();
                int pos;
                for(int i=0;i<6;i++) if(s[i]=='0') pos=i;
                int x=pos/3,y=pos%3;
                for(int i=0;i<4;i++){
                    int xx=x+dx[i],yy=y+dy[i];
                    if(xx<0||xx>=2||yy<0||yy>=3) continue;
                    string t=s;
                    swap(t[x*3+y],t[xx*3+yy]);
                    if(t==ans) return len;
                    if(!st.count(t)){
                        st.insert(t);
                        q.push(t);
                    }
                }
            }
            len++;
        }
        return -1;
    }
};

时间复杂为指数级别。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值