zoukankan      html  css  js  c++  java
  • POJ 1753 Flip game状态压缩+广搜

    题意
    有4*4的16个方格,每个方格有黑白两种颜色,每次点击方格后,被点击方格本身及其上下左右的方格都会改变颜色。给出一组状态,求将这组状态变为全白或者全黑至少需要点击几次。若无法达到,则输出Impossible。

    样例输入
    bwwb
    bbwb
    bwwb
    bwww

    样例输出
    4

    思路
    每个方格只有黑白两种颜色,且只有16个方格,因此可以把每个状态看作一个16位的二进制数(状态压缩),2^16=25536,因此可以用int来保存状态。然后就是BFS暴搜,直到状态为0或者65535(全1)为止。

    注意点
    65535种状态,因此数组要开到65536。

     1 #include <cstdio>
     2 #include <string.h>
     3 #include <queue>
     4 using namespace std;
     5 const int flip[16] = {0xC800, 0xE400, 0x7200, 0x3100, 0x8C80, 0x4E40, 0x2720, 0x1310, 0x8C8, 0x4E4, 0x272, 0x131, 0x8C, 0x4E, 0x27, 0x13};
     6 const int done = 65535;
     7 void BFS(int x)
     8 {
     9     int cnt[done+1];
    10     bool vis[done+1];
    11     cnt[x] = 0;
    12     vis[x] = true;
    13     queue<int> q;
    14     q.push(x);
    15     int top, temp;
    16     while(!q.empty())
    17     {
    18         top = q.front();
    19         for(int i=0; i<16; ++i)
    20         {
    21             temp = top ^ flip[i];
    22             if(!vis[temp])
    23             {
    24                 cnt[temp] = cnt[top] + 1;
    25                 if(!temp || temp == done)
    26                 {
    27                     printf("%d
    ", cnt[temp]);
    28                     return ;
    29                 }
    30                 vis[temp] = true;
    31                 q.push(temp);
    32             }
    33         }
    34         q.pop();
    35     }
    36     printf("Impossible
    ");
    37 }
    38 int main(void)
    39 {
    40     int x = 0;
    41     for(int i=0; i<4; ++i)
    42     {
    43         for(int j=0; j<4; ++j)
    44             x = (x << 1) + (getchar() == 'b' ? 1 : 0);
    45         getchar();
    46     }
    47     if(!x || x == done)
    48         printf("0
    ");
    49     else
    50         BFS(x);
    51 }
  • 相关阅读:
    【ci框架】ci框架目录结构分析
    php CI框架
    jQuery boxy弹出层插件中文演示及讲解
    Jenkins构建报错(Jenkins is reserved for jobs with matching label expression)解决办法
    redis缓存数据架构实战
    Git免密码pull&push
    Maven搭建Nexus私有仓库
    Windows使用filezilla搭建FTP服务器
    CentOS7.4使用yum安装MySQL5.6
    MySQL数据库连接池导致页面登录无法查询问题解决过程
  • 原文地址:https://www.cnblogs.com/corvey/p/5263818.html
Copyright © 2011-2022 走看看