POJ1753 Flip Game 翻转棋盘 方法:bit + BFS

题目描述:4*4黑白棋盘,点击一个棋子,则它的四周及本身变化颜色,求变为纯色的最短步数。

方法:用BFS求最短步数,bit存储状态,共有2^16=65536种状态。

 

  1 #include <iostream>
  2 #include <cstdio>
  3 #include <cstring>
  4 #include <queue>
  5 
  6 using namespace std;
  7 
  8 bool visit[65536]; // 共有2^16个状态
  9 
 10 int dir[4][2] = {{0,1}, {-1,0}, {0,-1}, {1,0}};
 11 int change[16]; // 根据dir[4][2]确定变化位状态, 通过异或
 12 
 13 struct Node {
 14     int state;
 15     int step;  
 16 };
 17 
 18 void initChange() 
 19 {
 20     int x, y, state, temp;
 21     
 22     for (int i = 0; i < 4; ++i) {
 23         for (int j = 0; j < 4; ++j) {
 24             state = 0;
 25             state = 1 << (3-i)*4+3-j;
 26 
 27             for (int t = 0; t < 4; ++t) {
 28                 x = i + dir[t][0];
 29                 y = j + dir[t][1];
 30 
 31                 if (x < 0 || x > 3 || y < 0 || y > 3) {
 32                     continue;    
 33                 } else {
 34                     state ^= 1 << (3-x)*4+3-y;     
 35                 }
 36             }
 37             change[i*4+j] = state;
 38         }
 39     }    
 40 }
 41 
 42 int bfs(int state)
 43 {
 44     queue<Node> q;
 45     Node cur, next;
 46     cur.state = state;
 47     cur.step = 0;
 48     q.push(cur);
 49     memset(visit, false, sizeof(visit));
 50 
 51     if (cur.state == 0 || cur.state == 0xffff) // 初始就是全w或b的情况
 52         return cur.step;    
 53 
 54     while (!q.empty()) {
 55         cur = q.front();
 56         q.pop();
 57 
 58         for (int i = 0; i < 16; ++i) {   // bfs
 59             next.state = cur.state ^ change[i];
 60             next.step = cur.step + 1;
 61 
 62             if (visit[next.state]) 
 63                 continue;
 64 
 65             if (next.state == 0 || next.state == 0xffff) 
 66                 return next.step;    
 67         
 68             visit[next.state] = true;
 69             q.push(next);    
 70         }
 71     }
 72 
 73     return -1;
 74 }
 75 
 76 int main()
 77 {
 78     int state, ans;
 79     char ch[4][4];
 80 
 81     // freopen("temp.txt", "r", stdin);
 82     initChange();
 83     state = 0; 
 84     for (int i = 0; i < 4; ++i) {
 85         scanf("%s", ch[i]);    
 86         for (int j = 0; j < 4; ++j) {
 87             if (ch[i][j] == 'b') {
 88                 state ^= 1 << (3-i)*4+3-j;
 89             }
 90         }
 91     }
 92 
 93     ans = bfs(state);
 94 
 95     if (ans == -1) 
 96         puts("Impossible");
 97     else 
 98         cout << ans << endl;
 99     
100     return 0;
101 }

 

你可能感兴趣的:(POJ1753 Flip Game 翻转棋盘 方法:bit + BFS)