• LG2578 「ZJOI2005」九数码游戏 bfs


    问题描述

    LG2578


    题解

    string+map去重。

    bfs即可。


    (mathrm{Code})

    #include<bits/stdc++.h>
    using namespace std;
    
    void read(int &x){
        x=0;char ch=1;int fh;
        while(ch!='-'&&(ch>'9'||ch<'0')) ch=getchar();
        if(ch=='-') ch=getchar(),fh=-1;
        else fh=1;
        while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
        x*=fh;
    }
    
    string que[1000003];
    int f,r;
    map<string,bool>s;
    int pre[1000003];
    
    void change1(string &s){
    	string bf="";
    	bf+=s[3];
    	bf+=s[0];
    	bf+=s[1];
    	bf+=s[6];
    	bf+=s[4];
    	bf+=s[2];
    	bf+=s[7];
    	bf+=s[8];
    	bf+=s[5];
    	s=bf;
    }
    
    void change2(string &s){
    	string bf="";
    	bf+=s[0];
    	bf+=s[1];
    	bf+=s[2];
    	bf+=s[5];
    	bf+=s[3];
    	bf+=s[4];
    	bf+=s[6];
    	bf+=s[7];
    	bf+=s[8];
    	s=bf;
    }
    
    void println(string s){
    	int cnt=0;
    	for(int i=1;i<=3;i++){
    		for(int j=1;j<=3;j++){
    			printf("%d ",s[cnt]-'0');++cnt;
    		}
    		puts("");
    	}
    }
    
    void readln(string &s){
    	char c;int x;
    	for(int i=1;i<=3;i++){
    		for(int j=1;j<=3;j++){
    			read(x);
                c=(char)(x+'0');
    			s+=c;
    		}
    	}
    }
    
    void endit(int x){
    	int p=x;stack<int>st;int zzkakioi=0;
    	while(p){
    		st.push(p);zzkakioi++;
    		p=pre[p];
    	}
    	--zzkakioi;
    	printf("%d
    ",zzkakioi);
    	while(st.size()){
    		int x=st.top();
    		println(que[x]);
    		puts("");
    		st.pop();
    	}
    	exit(0);
    }
    
    bool check(string s){
    	return s=="012345678";
    }
    
    int main(){
        readln(que[f=r=1]);
        s[que[1]]=1;
        while(f<=r){
            string x=que[f];
            if(check(x)) endit(f);
            change1(x);
            if(s[x]==0){
                s[x]=1;++r;
                que[r]=x;pre[r]=f;
            }
            x=que[f];
            change2(x);
            if(s[x]==0){
            	s[x]=1;++r;
            	que[r]=x;pre[r]=f;
            }
            ++f;
        }
        puts("UNSOLVABLE");
        return 0;
    }
    
  • 相关阅读:
    Python学习 day01打卡
    Python变量常量及注释
    Python基础简介
    「ubuntu」sudo命令卡住
    「ubuntu」sudo无密码
    「ubuntu」Ubuntu Recovery模式下只读问题
    「ubuntu」在Ubuntu Server 16.04 LTS下安装VMware Tools(转)
    「mysql」设置utf8编码
    「hive」hive2.3.0配置derby
    「hadoop」log4j参考
  • 原文地址:https://www.cnblogs.com/liubainian/p/11608965.html
Copyright © 2020-2023  润新知