蒟蒻求调!
查看原帖
蒟蒻求调!
1368930
chenzhexuan1楼主2024/8/26 17:40

在bfs函数中第34行,如果使用了标记数组(vis数组)答案会不对,但是不用标记数组会mle,有什么方法解决?代码如下:

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct Node{
	int x,y,s;
	string t;
	Node(){}
	Node(int a,int b,int c,string d):x(a),y(b),s(c),t(d){}
};
string sts;
char mp[5][5];
int dx[4]={0,0,-1,1},dy[4]={1,-1,0,0},stx,sty;
bool vis[5][5];
int bfs(int stx,int sty,string sts){
	queue<Node> que;
	que.push(Node(stx,sty,0,sts));
	vis[stx][sty]=true;
	while(!que.empty()){
		Node u=que.front();
		que.pop();
		if(u.t=="123804765")return u.s;
		for(int i=0;i<4;i++){
			int x=u.x+dx[i],y=u.y+dy[i],s=u.s+1;
			string t=u.t;
			char mpt[5][5];
			int l=0;
			for(int j=1;j<=3;j++){
				for(int k=1;k<=3;k++){
					mpt[j][k]=t[l];
					l++;
				}
			}
			if(1<=x&&x<=3&&1<=y&&y<=3){
				swap(mpt[x][y],mpt[u.x][u.y]);
				string t_new="";
				for(int j=1;j<=3;j++){
					for(int k=1;k<=3;k++)t_new+=mpt[j][k];
				}
				que.push(Node(x,y,s,t_new));
			}
		} 
	}
	return -1;
}
int main(){
	for(int i=1;i<=3;i++){
		for(int j=1;j<=3;j++){
			cin>>mp[i][j];
			if(mp[i][j]=='0')stx=j,sty=i;
			sts+=mp[i][j];
		}
	}
	cout<<bfs(stx,sty,sts);
}
2024/8/26 17:40
加载中...