• a*骑士精神


    这题显然是一道a*的模板题

    本人这里才用a*剪枝的dfs方法

    具体做法如下

    直接上代码吧,没什么好讲的,就是利用目前状态与目标有几个不同的求估价函数h

     1 #include<cstdio>//by Yae Sakura 
     2 #include<iostream>
     3 using namespace std;
     4 int targe[6][6]={0,0,0,0,0,0,0,1,1,1,1,1,0,0,1,1,1,1,0,0,0,-1,1,1,0,0,0,0,0,1,0,0,0,0,0,0};
     5 int ans=16;
     6 int w[6][6];
     7 int dx[9]={0,1,1,-1,-1,2,2,-2,-2};
     8 int dy[9]={0,2,-2,2,-2,1,-1,1,-1};
     9 int geth()
    10 {
    11     int h=0;
    12     for(int i=1;i<=5;i++)
    13     for(int j=1;j<=5;j++)
    14     if(w[i][j]!=targe[i][j])
    15     h++;
    16     return h;
    17 }
    18 void dfs(int g,int x,int y)
    19 {
    20     int h=geth();
    21     if(h==0)
    22     {
    23         ans=min(ans,g);
    24         return;
    25     }
    26     if(g>ans)
    27     return;
    28     if(g+h>ans)
    29     return;
    30     for(int i=1;i<=8;i++)
    31     if(x+dx[i]<=5&&x+dx[i]>=1&&y+dy[i]<=5&&dy[i]+y>=1)
    32     {
    33         swap(w[y][x],w[y+dy[i]][x+dx[i]]);
    34         dfs(g+1,x+dx[i],y+dy[i]);
    35         swap(w[y][x],w[y+dy[i]][x+dx[i]]);
    36     }
    37 }
    38 int main()
    39 {
    40     int t;
    41     scanf("%d",&t);
    42     for(int i=1;i<=t;i++)
    43     {
    44         int x,y;
    45         for(int i=1;i<=5;i++)
    46         for(int j=1;j<=5;j++)
    47         {
    48             char s;
    49             cin>>s;
    50             if(s=='0')
    51             w[i][j]=0;
    52             if(s=='1')
    53             w[i][j]=1;
    54             if(s=='*')
    55             {
    56                 w[i][j]=-1;
    57                 y=i;
    58                 x=j;
    59             }
    60         }
    61         dfs(0,x,y);
    62         if(ans==16)
    63         printf("-1
    ");
    64         else
    65         printf("%d
    ",ans);
    66         ans=16;
    67     }
    68 } 
    View Code

    12月29日 女装纪念

    By Yae Sakura

  • 相关阅读:
    app store connect待提交修改版本号
    tableview无法调用touchesBegan
    UISearchController遇坑总结
    中文空格 占位符(OC)
    OC校验字符串是否每个字符都相同
    IPA processing failed
    关于静态代码块和非静态代码块执行顺序(了解这些你就了解所有)
    MapReduce
    大数据---HDFS写入数据的过程
    大数据之--------hadoop存储(HDFS)
  • 原文地址:https://www.cnblogs.com/mzh2017/p/8146534.html
Copyright © 2020-2023  润新知