1 해설

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

    C++ :

    #include<bits/stdc++.h>
    using namespace std;
    //上下左右 
    int dx[]={-1,1,0,0};
    int dy[]={0,0,-1,1};
    char ops[]={'u','d','l','r'};
    #define x first
    #define y second
    map<string,pair<char,string> > pre;
    void bfs(string s)
    {
        queue<string> q;
        map<string,int> dist;
        q.push(s);
        dist[s]=0;
        string es="12345678x";
        while(q.size())
        {
            string t=q.front();
            q.pop();
            if(t==es) //找到终点 
            {
                return ;
            }  
            int k=t.find('x'); //寻找x的位置 
            int x=k/3,y=k%3; //映射 
            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) continue;
                string str=t;
                int kk=a*3+b;
                swap(str[kk],str[k]); //得到由t走到的字符串 
                if(dist.count(str)==0) //没有在哈希表中出现过 
                {
                    dist[str]=dist[t]+1;
                    pre[str]={ops[i],t};
                    q.push(str);
                }
                 
            }
        }
    }
    int main()
    {
        string s;
        for(int i=0;i<9;i++)
        {
            char ch;
            cin>>ch;
            s=s+ch;
        }
        bfs(s);
    	string res;
        string end="12345678x";
        int i=0;
        while(end!=s)
        {
        	res+=pre[end].x;
        	end=pre[end].y;
    	}
    	reverse(res.begin(),res.end());
    	cout<<res;
        return 0;
    }
    
    • 1

    정보

    ID
    777
    시간
    1000ms
    메모리
    128MiB
    난이도
    (N/A)
    태그
    제출 기록
    0
    맞았습니다.
    0
    아이디