ZOJ 2097 棋盤走路

來源:互聯網
上載者:User

#include<iostream>
#include<queue>
using namespace std;
#define max 1001                  //這裡最後不能加分號,否則他把 max 的值定義為“1001;”
int s[10][10];
int t[10][10][5];
int map[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int i,j,k,x,y;

 

struct node
{
    int x;
    int y;
    int state;
}start,temp,end;

                              //本題關鍵是不同的state的cost值導致的最少值有所不同,所以都要保留
void insert()
{
    for(i=1;i<9;i++)
        for(j=1;j<9;j++)
            cin>>s[i][j];

    for(i=1;i<=8;i++)
    {
        for(j=1;j<=8;j++)
        {
            for(k=1;k<=4;k++)
                t[i][j][k]=100000000;
        }
    }
    t[start.y][start.x][1]=0;
}

void bfs(queue<struct node>qu)
{
    int v,ans;
    while(!qu.empty())
    {
        temp=qu.front();
        qu.pop();
        for(i=0;i<4;i++)
        {
            x=temp.x+map[i][0];
            y=temp.y+map[i][1];
            if(x>0 && x<9 && y>0 && y<9 )
            {                                       

                start.x=x;
                start.y=y;
                v=t[temp.y][temp.x][temp.state]+temp.state*s[y][x];
                start.state=(temp.state*s[y][x]%4)+1;
                if(v<t[y][x][start.state])
                {
                    qu.push(start);
                    t[y][x][start.state]=v;
                }
                
    //            s[y][x]=max;
            }
        }
    }
    ans=t[end.y][end.x][1];
    for(i=2;i<=4;i++)
    {
        if(ans>t[end.y][end.x][i])
            ans=t[end.y][end.x][i];
    }
    cout<<ans<<endl;
}
                    //清為128之前的數就是一個大數16843009等,清128之後就是負數,清0就是0

int main()
{
    int a[2],b[2];
    while(cin>>a[0]>>a[1]>>b[0]>>b[1] && !(a[0]==0&&a[1]==0&&b[0]==0&&b[1]==0))
    {
        
//        memset(s,max,sizeof(s));          //這裡memset好像不能讓整個數組s都清值,所以上面不能省
        
        queue<struct node>qu;
        start.x=a[1];
        start.y=a[0];
        start.state=1;
        insert();
        s[a[0]][a[1]]=max;
        
        end.x=b[1];
        end.y=b[0];
        qu.push(start);
        bfs(qu);
        
    }
    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.