题意:冰箱有16个开关,按4*4的矩阵排列。每改变一个开关的状态,与它同行同列的所有开关也要全部改变状态。求出打开冰箱所需要的最少调整次数。
题解:DFS应该也可以。
#include <queue>
#include <iostream>
using namespace std;
queue<int> que;
int step[1<<16];
int point[1<<16];
int cell[] = { 4383, 8751, 17487, 34959, 4593, 8946, 17652, 35064, 7953, 12066, 20292, 36744, 61713, 61986, 62532, 63624 };
int main()
{
char ch;
int i, pos = 0;
for ( i = 0; i < 16; i++ )
{
cin >> ch;
if ( ch == '+' )
pos += ( 1 << i );
}
memset(step,-1,sizeof(step));
memset(point,-1,sizeof(point));
que.push ( pos );
step[pos] = 0;
int current, next;
while ( !que.empty () )
{
current = que.front ();
que.pop();
for ( i = 0; i < 16; i++ )
{
next = current ^ cell[i];
if ( step[next] == -1 )
{
point[next] = i;
step[next] = step[current] + 1;
que.push ( next );
}
if ( next == 0 )
{
cout << step[current] + 1 << endl;
while ( next != pos )
{
cout << point[next] / 4 + 1 << ' ' << point[next] % 4 + 1 << endl;
next = next ^ cell[point[next]];
}
return 0;
}
}
}
return 0;
}