zoukankan      html  css  js  c++  java
  • 九宫重排

    这题和之前的九宫幻方一样,都属于水题。不过这题的思维相对要复杂一点,不过bfs搜一遍也万事大吉了。

    需要注意的是去重。用这题用set去重足矣,因为数据量相对不是特别大。如果对hash熟悉可以用写个hash函数去重

    还有就是目标点的移动。我在草稿纸上推了一下,就推出了公式。不用专门转化为二维数组进行移动、交换,减少编码复杂度

    AC代码:

    #include <stdio.h>
    #include <memory.h>
    #include <math.h>
    #include <string>
    #include <string.h>
    #include <vector>
    #include <set>
    #include <stack>
    #include <queue>
    #include <algorithm>
    #include <map>
    
    
    #define I scanf
    #define OL puts
    #define O printf
    #define F(a,b,c) for(a=b;a<c;a++)
    #define FF(a,b) for(a=0;a<b;a++)
    #define FG(a,b) for(a=b-1;a>=0;a--)
    #define LEN 100
    #define MAX 0x06FFFFFF
    #define V vector<int>
    
    typedef long long ll;
    
    using namespace std;
    
    set<string> vis; 
    
    bool notVis(string s){
        if(vis.find(s)==vis.end()){
            vis.insert(s);
            return 1;
        }else{
            return 0;
        }
    }
    
    int main(){
    //    freopen("D:/CbWorkspace/blue_bridge/九宫重排_2.txt","r",stdin);
        char buf[10];
        gets(buf);
        string S(buf);
        gets(buf);
        string E(buf);
        queue<string> q;
        q.push(S);
        int cnt=0;
        while(!q.empty()){
            int sz=q.size();
            while(sz--){
                string t=q.front();
                q.pop();
                if(t==E){
                    O("%d
    ",cnt);
                    return 0;
                }
                int pos=t.find('.');
                if(pos>=3){//
                    string tmp=t;
                    swap(tmp[pos],tmp[pos-3]);
                    if(notVis(tmp)) q.push(tmp);
                }
                if(pos<6){//
                    string tmp=t;
                    swap(tmp[pos],tmp[pos+3]);
                    if(notVis(tmp)) q.push(tmp);
                }
                if(pos%3>0){//
                    string tmp=t;
                    swap(tmp[pos],tmp[pos-1]);
                    if(notVis(tmp)) q.push(tmp);
                }
                if(pos%3<2){//
                    string tmp=t;
                    swap(tmp[pos],tmp[pos+1]);
                    if(notVis(tmp)) q.push(tmp);
                }             
            }
            cnt++;
        }
        O("%d
    ",-1);
        return 0;
    }
  • 相关阅读:
    原型设计作业
    案例分析作业
    编程作业
    阅读任务
    自我介绍
    5 20210420-1 团队作业1—团队展示
    3 20210405-1 案例分析作业
    阅读任务
    自我介绍
    原型设计
  • 原文地址:https://www.cnblogs.com/TQCAI/p/8643426.html
Copyright © 2011-2022 走看看