题意:一个4 * 4 的棋盘, 翻转一个点的时候其上下左右都会翻转,求将它们翻转成相同的颜色至少要多少步(全部置为白棋或者是黑棋)。
思路:纯 BFS,有一点小技巧,很巧妙的将棋盘的黑白转换成0101,然后用异或取反。
10945224 | NY_lv10 | 1753 | Accepted | 564K | 32MS | C++ | 988B | 2012-10-23 09:53:08 |
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include <iostream> #include <queue> using namespace std; int arr[16]={0xc800,0xe400,0x7200,0x3100,0x8c80,0x4e40,0x2720,0x1310,0x08c8,0x04e4,0x0272,0x0131,0x008c,0x004e,0x0027,0x0013}; //取反数组 queue<int> que; bool used[65536]; int step[65536]; //保存步数 int main() { int num; int i; char ch; num = 0; for (i=0; i<16; i++) { cin>>ch; num <<= 1; // num *= 10 if (ch == 'b') num += 1; } /* BFS */ while (!que.empty()) que.pop(); memset(used, false, sizeof(used)); que.push(num); step[num] = 0; used[num] = true; int tmp; bool flags = false; while (!que.empty() && !flags) { tmp = que.front(); que.pop(); for (i=0; i<16; i++) { num = tmp; num ^= arr[i]; if (!used[num]) { used[num] = true; step[num] = step[tmp] + 1; que.push(num); } if(num == 0 || num == 65535) { flags = true; //已经翻转好了 break; } } } if (flags) cout<<step[num]<<endl; else cout<<"Impossible"<<endl; return 0; }