zoukankan      html  css  js  c++  java
  • [暑假集训Day3T2]骑士问题

    标准的广搜。

    采用队列保存形态,如果不会广搜的可以多看看PJ知识点。由于输入多组数据,每次标记数组要清空,每次队列元素也都要清空。

    参考代码如下:

     1 #include<iostream>
     2 #include<cstring>
     3 #include<queue>
     4 using namespace std;
     5 int t,n,x1,y1,x2,y2;
     6 int dx[8]={-1,1,2,2,1,-1,-2,-2},dy[8]={2,2,1,-1,-2,-2,-1,1};
     7 bool f[1305][1305];
     8 struct node
     9 {
    10     int x,y,step;
    11 };
    12 int read()
    13 {
    14     int x=0,f=1;char ch=getchar();
    15     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    16     while(ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
    17     return x*f;
    18 }
    19 void bfs()
    20 {
    21     node h;
    22     h.x=x1;h.y=y1;h.step=0;
    23     queue<node>q;
    24     q.push(h);
    25     f[h.x][h.y]=1;
    26     while(!q.empty())
    27     {
    28         node k=q.front();
    29         q.pop();
    30         for(int i=0;i<=7;i++)
    31         {
    32             int xx=k.x+dx[i],yy=k.y+dy[i];
    33             if(f[xx][yy]||xx<0||yy<0||xx>n||yy>n)continue;
    34             node pus;
    35             pus.x=xx;pus.y=yy;pus.step=k.step+1;
    36             f[xx][yy]=1;
    37             if(xx==x2&&yy==y2)
    38             {
    39                 cout<<pus.step<<endl;
    40                 return;
    41             }
    42             q.push(pus);
    43         }
    44     }
    45 }
    46 int main()
    47 {
    48     //freopen("1.in","r",stdin);
    49     t=read();
    50     while(t--)
    51     {
    52         memset(f,0,sizeof(f));
    53         n=read();x1=read();y1=read();x2=read();y2=read();
    54         if(x1==x2&&y1==y2)cout<<0<<endl;
    55         bfs();
    56     }
    57     return 0;
    58 }
    View Code
  • 相关阅读:
    springboot 项目部署到服务器
    Thymeleaf的注意项
    springboot定时器
    springboot
    随笔
    mysql数据库连接超过8小时失效的解决方案(springboot)
    Druid连接池与spring配置
    IDEA快捷键
    jsonp解决跨域,用div,css,js,jq实现textarea自适应高度
    mysql的查询、子查询及连接查询(商城查询常用)
  • 原文地址:https://www.cnblogs.com/szmssf/p/11172908.html
Copyright © 2011-2022 走看看