POJ 3221 Diamond Puzzle.

來源:互聯網
上載者:User

標籤:poj 3221   diamond puzzle.   a diamond puzzle is   

~~~~

題目連結:http://poj.org/problem?id=3221

顯然是BFS找最優解,可是終止條件不好寫,看到有一隻隊交上去一直TLE。

比賽完了看題解原來是以目標狀態為起點,BFS給每個狀態打表,用一個map映射存起來。

~~~~

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<string>#include<queue>#include<map>using namespace std;char str[10];char s[10]="0123456";map<string,int> v; //狀態映射map<string,int>ans; //答案映射struct node{    int t;    char s[10];};//分別在0~6位置可以到達的目標位置,以-1結束。int dir[7][4]={    {2,4,6,-1},{2,6,-1},{1,0,3,-1},{2,4,-1},    {3,0,5,-1},{4,6,-1},{1,0,5,-1}        };int Find(char* s){    for(int i=0;i<7;i++)        if(s[i]=='0') return i;}int bfs(){    queue<node> q;    node cur,next;    strcpy(cur.s,s);cur.t=0;    q.push(cur);    v[cur.s]=1;    ans[cur.s]=0;    while(!q.empty())    {        cur=q.front(); q.pop();        int pos=Find(cur.s); //'0'的位置。        for(int i=0;dir[pos][i]!=-1;i++)        {            char temp[10];            strcpy(temp,cur.s);            //交換‘0’和和相應能去的位置            swap(temp[pos],temp[dir[pos][i]]);            if(!v[temp])            {                v[temp]=1;                strcpy(next.s,temp);                next.t=cur.t+1;                ans[next.s]=next.t;                q.push(next);            }        }    }}int main(){    v.clear();    ans.clear();    bfs();    int T;    scanf("%d",&T);    while(T--)    {        scanf("%s",str);        if(strcmp(str,s)==0) puts("0");        else printf("%d\n",ans[str]==0?-1:ans[str]);    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.