POJ Flip Game(BFS + 位运算)
2015-08-21 15:20
344 查看
题目链接:http://poj.org/problem?id=1753
一个翻转会带动四周,求至少要几次才能全白或者全黑,不能输出Impossible。
总共也就1 << 16 种状态,用数的位来存储就可以了。然后bfs找最快的, x ^ (1 << j) 是将x的第j位取反,怎么取反,看看棋子的位置就可以了 。
一个翻转会带动四周,求至少要几次才能全白或者全黑,不能输出Impossible。
总共也就1 << 16 种状态,用数的位来存储就可以了。然后bfs找最快的, x ^ (1 << j) 是将x的第j位取反,怎么取反,看看棋子的位置就可以了 。
#include<iostream> #include<cstring> #include<cmath> #include<cstdio> #include<algorithm> #include <queue> using namespace std; char mp[5][5]; bool vis[1 << 17]; int start = 0; struct node { int state, rds; }; inline int solve(int x, int now) { now ^= 1 << x; if(x % 4 != 0) { now ^= 1 << (x-1); } if(x < 12) { now ^= 1 << (x+4); } if(x > 3) { now ^= 1 << (x-4); } if(x % 4 != 3) { now ^= 1 << (x+1); } if(!vis[now]) { vis[now] = 1; return now; } return -1; } void bfs() { queue<node> que; node cur; cur.state = start; cur.rds = 0; que.push(cur); vis[start] = 1; while (!que.empty()) { cur = que.front(); que.pop(); if(cur.state == 0 || cur.state == (1 << 16) - 1) { printf("%d\n", cur.rds); return ; } for (int i = 0; i < 16; i ++) { int tmp = solve(i, cur.state); if(tmp != -1) { node N; N.state = tmp; N.rds = cur.rds + 1; que.push(N); } } } printf("Impossible\n"); } int main () { for (int i = 0; i < 4; i ++) { scanf("%s", mp[i]); for (int j = 0; j < 4; j ++) { start = (start << 1) + (mp[i][j] == 'b' ? 1 : 0); } } bfs(); return 0; }
相关文章推荐
- mongodb 批量更新,删除
- 齐纳二极管
- Java类加载器
- POJ 3020 Antenna Placement
- 自定义控件(支持模板)
- ListView滑动到底部的监听
- PostgreSQL使用pg_basebackup搭建主备流复制环境
- Processing an OS Descriptor request -- Remote Desktop Protocol
- 指定初始化方法
- jQuery实现垂直半透明手风琴特效代码分享
- linux 统计 程序运行时间
- retain,copy,assign,strong,weak,autorelease,nonatomic,atomic等得使用及区别
- 长短信与短信签名
- [MongoDB] - Window7下安装及BSON基本介绍
- 小票打印机打印出空白
- 神奇的make自动生成include file的功能
- centos 6.7下安装redmine+svn+apache
- nucleo stmcubemx 按键中断测试
- c++ 中文分词介绍
- C语言提高之技术模型层次、学习标准、特点、内存四区、函数调用模型