写了两个测试,发现对着啊,求大神指正
查看原帖
写了两个测试,发现对着啊,求大神指正
1278024
qwer123_楼主2024/7/28 01:18
#include<iostream>
#include<string>
#include<unordered_map>
#include<queue>
using namespace std;
int dx[] = {-1,0,1,0};
int dy[] ={0,1,0,-1};
string end1 = "123804765";//将目标状态存起来
unordered_map<string,int> dist;//存距离
unordered_map<string,int>vis;//表示当前状态,方便双向广搜
queue<string> q;
int bfs(string start){
    q.push(start);
    q.push(end1);//将初始状态和末尾状态都入队
    dist[start] = 0,dist[end1] = 0;//距离初始化
    vis[start] = 1,vis[end1] = 2;
    while(q.size()){
        auto t = q.front();
        q.pop();//取出队头,同时队头出队
        cout<<"pop:"<<t<<endl;
        int a = t.find('0');//找到字符0的位置,方便一维转二维
        int x1 = a / 3, y1 = a % 3;
        for(int i = 0; i < 4; i ++){
            int x2 = dx[i] + x1, y2 = dy[i] + y1;
            if(x2 < 0 || x2 >= 3 || y1 < 0 || y2 >= 3) continue;
            int temp = x2 * 3 + y2;//转换成字符串中的位置
            string new_state = t;
            cout<<"a:"<<a<<" "<<"temp:"<<temp<<endl;
            swap(new_state[a],new_state[temp]);//交换两个字母位置,即变成下一个状态
            
            if(vis[t] + vis[new_state] == 3){
                return dist[new_state] + dist[t] + 1;
            }
            if(!dist.count(new_state))//如果这个状态是一个新状态
            {
                dist[new_state] = dist[t] + 1;//更新距离
                vis[new_state] = vis[t];//同时更新状态
                q.push(new_state);
                cout<<"new_state:"<<new_state<<endl;
            }
        }
    }
    return -1;
    
}
int main(){
    string s;
    cin>>s;
    int res = bfs(s);
    cout<<res<<endl;
    return 0;
    
}
2024/7/28 01:18
加载中...