acm-uva11352解题报告

题目地址:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=25&page=show_problem&problem=2327

题目大意:王不可以走到马一步所能走到的位置上,终点除外,求最短路长度

解题方法:标准BFS

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <queue>
using namespace std;
#define MAXN 110
int map[MAXN][MAXN],map2[MAXN][MAXN],book[MAXN*MAXN];
char cmap[MAXN][MAXN];

const int N=105;
const int hd[8][2]={{-2,-1},{-1,-2},{-2,1},{-1,2},{2,-1},{1,-2},{2,1},{1,2}};
const int kd[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
const int INF=0x3f3f3f3f;

int main()
{
    int t;cin>>t;
    while(t--)
    {
        memset(map,-1,sizeof(map));
        memset(map2,-1,sizeof(map2));
        int m,n;cin>>m>>n;getchar();
        int start,finish,zx,zc;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                char ch=getchar();
                if(ch=='.')map[i][j]=0;
                else if(ch=='Z'){map[i][j]=1;map2[i][j]=1;}
                else if(ch=='A'){map[i][j]=0;start=i*n+j;}
                else if(ch=='B'){map[i][j]=0;finish=i*n+j;zx=i;zc=j;}
            }
            getchar();
        }
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(map2[i][j]==1)
                {
                    for(int qw=0;qw<8;qw++)
                    {
                        int dx=i+hd[qw][0],dy=j+hd[qw][1];
                        if(dx>=0&&dx<m&&dy>=0&&dy<n)map[dx][dy]=1;
                    }
                }
            }
        }
        map[zx][zc]=0;

        /*for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                cout<<map[i][j]<<" ";
            }
            cout<<endl;
        }*/

        queue<int>q;
        memset(book,-1,sizeof book);
        q.push(start);book[start]=0;
        while (!q.empty())
        {
            int u=q.front();
            q.pop();
            if (u==finish)break;
            int x=u/n;
            int y=u%n;
            for (int i=0;i<8;i++)
            {
                int dx=x+kd[i][0],dy=y+kd[i][1];
                int v=dx*n+dy;
                if (dx>=0&&dx<m&&dy>=0&&dy<n&&map[dx][dy]==0&&book[v]==-1)
                {
                    book[v]=book[u]+1;
                    q.push(v);
                }
            }
        }

        /*for(int i=0;i<m*n;i++)
        {
            cout<<book[i]<<" ";
            if((i+1)%n==0)cout<<endl;
        }*/
        
        if(book[finish]==-1)cout<<"King Peter, you can't go now!"<<endl;
        else cout<<"Minimal possible length of a trip is "<<book[finish]<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值