跳到正文

个人记录

7.12

Owen0130约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月12日
收录
2025年12月12日
更新
2026年11月3日
篇幅
约 4 分钟

版本

  1. v1当前

八数码难题

#include<bits/stdc++.h>

using namespace std;

string a;

string re=“123804765”;

int x2;

struct lnt{

C++
string s;
int x;
int z;

};

int dx[5]={0,1,3,-1,-3};

queue<lnt> s;

map<string,bool> mp;//用mp记录走没走过

int main(){

C++
cin>>a;
for(int i=0;i<9;i++){
	if(a[i]=='0') x2=i;
}
s.push({a,x2,0});
while(s.size()){
	lnt f=s.front();
	//cout<<f.s<<endl;
	if(f.s==re){
		cout<<f.z;
		return 0;
	}
	for(int i=1;i<=4;i++){
        int fx=f.x+dx[i];
        //判断4种方式
		if(i==1&&(f.x==2||f.x==5||f.x==8)) continue;
		if(i==2&&(f.x==6||f.x==7||f.x==8)) continue;
		if(i==3&&(f.x==0||f.x==3||f.x==6)) continue;
		if(i==4&&(f.x==0||f.x==1||f.x==2)) continue;
		string fs=f.s;
        int fz=f.z+1;
		swap(fs[fx],fs[f.x]);
		if(mp[fs]==0){
			mp[fs]=1;
			s.push({fs,fx,fz});
		}
	}
	s.pop();
}
return 0;

}

魔板 Magic Squares

#include<bits/stdc++.h>

using namespace std;

string a=“12348765”;起始点

string re="";

int x2;

struct lnt{

C++
string s;
int z;
string q;

};

int d[10];

queue<lnt> s;

map<string,bool> mp;

int main(){

C++
for(int i=0;i<8;i++){
	int q;
	cin>>q;
	re+=char(q+'1'-1);
	//cout<<re<<endl;
}
swap(re[4],re[7]);//更改输入

swap(re[5],re[6]);

C++
cout<<re<<endl;
s.push({a,0,""});
while(s.size()){
	lnt f=s.front();
	//cout<<f.s<<" "<<f.z<<endl;
	if(f.s==re){
		cout<<f.z<<endl<<f.q;
		return 0;
	}
	for(int i=1;i<=3;i++){
//3种走法
		if(i==1){
			string e=f.s;
			for(int j=0;j<4;j++) swap(e[j],e[j+4]);
			if(mp[e]==0){
                s.push({e,f.z+1,f.q+'A'});
                mp[e]=1;
            }
		}
		if(i==2){
			string e=f.s;
			char x=e[3];
			char y=e[7];
			for(int j=0;j<3;j++) e[j+1]=f.s[j];
			for(int j=4;j<7;j++) e[j+1]=f.s[j];
			e[0]=x;
			e[4]=y;
			if(mp[e]==0){
                s.push({e,f.z+1,f.q+'B'});
                mp[e]=1;
            }
		}
		if(i==3){
			string e=f.s;
			e[2]=f.s[1];
			e[1]=f.s[5];
			e[5]=f.s[6];
			e[6]=f.s[2];
            if(mp[e]==0){
                s.push({e,f.z+1,f.q+'C'});
                mp[e]=1;
            }
		}
	}
	s.pop();
}
return 0;

}

原文