1 条题解

  • 0
    @ 2023-10-18 10:01:26

    C++ :

    #include<bits/stdc++.h>
    using namespace std;
    #define x first
    #define y second
    int dx[]={-1,1,0,0};
    int dy[]={0,0,-1,1};
    typedef pair<int,string> PIS;
    int f(string state) //估计当前状态到终点状态的移动次数 
    {
    	int res=0;
    	for(int i=0;i<state.size();i++)
    	{
    		if(state[i]!='x')
    		{
    			int t=state[i]-'1';
    			res+=abs(i/3-t/3)+abs(i%3-t%3);
    		}
    	}
    	return res;
    }
    int bfs(string start)
    {
    	string end="12345678x";
    	map<string,int> dist;
    	priority_queue<PIS,vector<PIS>,greater<PIS>> heap;
    	dist[start]=0;
    	heap.push({f(start),start});
    	while(heap.size())
    	{
    		PIS t=heap.top();
    		heap.pop();
    		string state=t.y;
    		if(state==end) break;
    		int k=state.find('x');
    		int x=k/3,y=k%3; //坐标映射 
    		string source=state;
    		for(int i=0;i<4;i++)
    		{
    			int a=x+dx[i],b=y+dy[i];
    			if(a>=0&&a<3&&b>=0&&b<3)
    			{
    				state=source;
    				swap(state[3*x+y],state[a*3+b]);
    				if(dist[state]==0||dist[state]>dist[source]+1)
    				{
    					dist[state]=dist[source]+1;
    					heap.push({dist[state]+f(state),state});
    					//将起点到当前状态的距离+当前状态到终点的距离作为比较参数 
    				}
    			}
    		}
    	}
    	return dist[end];
    }
    int main()
    {
    	string start; //储存初始状态 
    	string seq; //储存所有数字字符 
    	char ch;
    	for(int i=0;i<9;i++)
    	{
    	    cin>>ch;
    		start+=ch;
    		if(ch!='x') seq+=ch;
    	}
    	int cnt=0;
    	for(int i=0;i<8;i++)
    	{
    		for(int j=i+1;j<8;j++)
    		{
    			if(seq[i]>seq[j])
    			{
    				cnt++;
    			}
    		}
    	}
    	if(cnt&1) cout<<"-1"; //当逆序对数量为奇数时,一定无解 
    	else cout<<bfs(start)<<endl;
    	return 0;
    }
    
    • 1

    信息

    ID
    788
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者