POJ 1753 - Flip Game (位运算 + BFS)
2016-08-29 21:31
525 查看
题目链接:
http://poj.org/problem?id=1753题意:
给一个4x4的棋盘,每次可以翻其中一个棋子,这个棋子上下左右的棋子也会被翻过来,问何时可以达到全白或全黑的状态。题解:
此题可以将棋盘上的状态转化为一个数字去存。将棋盘上状态看成一个2进制的数,1代表黑色0代表白色,可以翻的16个地方记做移动步数,这样只要把每次状态与这16种走法作异或运算即是翻过去的下一种状态。BFS即可。
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; struct Node { int state, step; }; int vis[65536]; int mov[16] = //16种状态转换,对应4*4的翻子位置 { 51200,58368,29184,12544, 35968,20032,10016,4880, 2248,1252,626,305, 140,78,39,19 }; int bfs(int state) { queue <Node> q; memset(vis,0,sizeof(vis)); Node cur,next; cur.state = state; cur.step = 0; q.push(cur); vis[cur.state] = 1; while(!q.empty()) { cur = q.front(); q.pop(); if(cur.state == 0 || cur.state == 65535) return cur.step; for(int i = 0; i < 16; i++) { next.state = cur.state ^ mov[i]; next.step = cur.step + 1; if(vis[next.state]) continue; if(next.state == 0 || next.state == 65535) return next.step; vis[next.state] = 1; q.push(next); } } return -1; } int main() { char ch[5][5]; while(~scanf("%s",ch[0])) { for(int i = 1 ; i < 4 ; i++) scanf("%s",ch[i]); int state = 0,bits = 0; for(int i = 3 ; i >= 0 ; i--) { for(int j = 3 ; j >= 0 ; j--) { if(ch[i][j] == 'b') state += (1 << bits); bits++; } } int ans = bfs(state); if(ans == -1) puts("Impossible"); else printf("%d\n",ans); } return 0; }
相关文章推荐
- poj_1753 Flip Game(dfs+枚举)/(bfs+位运算)
- 位运算-BFS-Flip Game-POJ 1753
- poj 1753 Flip Game(位运算+bfs)
- POj 1753--Flip Game(位运算+BFS)
- POJ 1753 Flip Game(bfs+位压缩运算)
- poj1753 Flip Game(BFS+位压缩)
- POJ 1753 Flip Game (黑白棋) (状态压缩+BFS)
- POJ1753,Flip Game,枚举,bfs都可以
- POJ 1753 Flip Game(bfs+状态压缩+位运算)
- zoj 2050 || poj 1753 Flip Game(状态压缩 简单BFS)
- POJ:1753-Flip Game(二进制+bfs)
- POJ1753 BFS+位运算
- [ACM] POJ 1753 Flip Game (枚举,BFS,位运算)
- POJ 1753 Flip Game(状态压缩BFS)
- poj 1753(位运算+BFS)
- POJ-1753 Flip Game【枚举+BFS+位存储】
- POJ 1753 bfs+位运算
- POJ 1753 Flip Game(bfs)
- poj1753 Flip Game 状态压缩+bfs
- POJ 1753 Flip Game(bfs)