Hdu--4255 螺旋矩阵

本文介绍了一种使用图论原理实现的最短路径查找算法,并通过实例演示了算法的应用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
int map[1009][1009],mark[1009][1009];
int a[1000001],xx,yy;
int dist[4][2]= {0,1,0,-1,1,0,-1,0};
struct node
{
    int x,y,step;
};
void grap()
{
    int c=1000000,x,y,z,b,i;
    x=1;
    y=1000;
    z=1;
    b=1000;
    while(c>0)
    {
        for(i=x; i<=y; i++)
            map[x][i]=c--;
        x++;
        for(i=x; i<=y; i++)
            map[i][y]=c--;
        y--;
        for(i=y; i>=z; i--)
            map[b][i]=c--;
        b--;
        for(i=b; i>z; i--)
            map[i][z]=c--;
        z++;
    }
}
void prim()
{
    int i,j;
    memset(a,0,sizeof(a));
    a[1]=1;
    for(i=2; i<=1000; i++)
        if(a[i]==0)
            for(j=2; i*j<=1000000; j++)
                a[i*j]=1;
}
int bfs(int aa,int bb)
{
    queue<node>q;
    node cur,next;
    cur.x=aa;
    cur.y=bb;
    cur.step=0;
    mark[aa][bb]=1;
    if(map[cur.x][cur.y]==yy)return cur.step;
    q.push(cur);
    while(!q.empty())
    {
        cur=q.front();
        q.pop();
        for(int i=0; i<4; i++)
        {
            next.x=cur.x+dist[i][0];
            next.y=cur.y+dist[i][1];
            if(next.x>=1&&next.y>=1&&next.x<=1000&&next.y<=1000&&mark[next.x][next.y]==0&&a[map[next.x][next.y]]==1)
            {
                next.step=cur.step+1;
                if(map[next.x][next.y]==yy&&a[map[next.x][next.y]]==1)return next.step;
                mark[next.x][next.y]=1;
                q.push(next);
            }
        }
    }
    return -1;
}
int main()
{
    int i,j,a,b,z=1;
    prim();
    grap();
    while(scanf("%d%d",&xx,&yy)!=-1)
    {
        for(i=1; i<=1000; i++)
        {
            for(j=1; j<=1000; j++)
                if(map[i][j]==xx)
                {
                    a=i;
                    b=j;
                    break;
                }
            if(j<=1000)
                break;
        }
        memset(mark,0,sizeof(mark));
        int ans=bfs(a,b);
        if(ans==-1)
            printf("Case %d: impossible\n",z++);
        else
            printf("Case %d: %d\n",z++,ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值