40分求调
查看原帖
40分求调
647306
ColinKIA楼主2023/3/10 21:05

样例一直输出6

#include <bits/stdc++.h>
using namespace std;
map <string,bool> vis;
int dx[5]={1,-1,4,-4};
string st,ed;
struct node{
	string a;
	int step;
	node(){}
	node(string A){
		a=A;
	}
};
void bfs(node s){
	s.step=0;
	queue<node>q;
	q.push(s);
	while(!q.empty()){
		node t1=q.front();
		q.pop();
		if(t1.a==ed){
			printf("%d\n",t1.step);
			return ;
		}
		for(int i=0;i<=15;i++){
			node t2=t1;
			for(int j=0;j<4;j++){
				if(i+dx[j]<0||i+dx[j]>15||t2.a[i]==t2.a[i+dx[j]]||t2.a[i]==0) continue;
				swap(t2.a[i],t2.a[i+dx[j]]);
				t2.step++;
				if(!vis[t2.a]){
					vis[t2.a]=1;
					q.push(t2);
				}
			}	
		}
	}
}
int main(){
	for(int i=1;i<=16;i++){
		char a;
		cin>>a;
		st+=a;
	}
	for(int i=1;i<=16;i++){
		char a;
		cin>>a;
		ed+=a;
	}
	if(st==ed){
		printf("0");
		return 0;
	}
	vis[st]=1;
	bfs(node(st));
	return 0;
}
2023/3/10 21:05
加载中...