描述
有9个时钟,排成一个3*3的矩阵。
现在需要用最少的移动,将9个时钟的指针都拨到12点的位置。共允许有9种不同的移动。如下表所示,每个移动会将若干个时钟的指针沿顺时针方向拨动90度。
移动 影响的时钟
1 ABDE
2 ABC
3 BCEF
4 ADG
5 BDEFH
6 CFI
7 DEGH
8 GHI
9 EFHI
输入
从标准输入设备读入9个整数,表示各时钟指针的起始位置。0=12点、1=3点、2=6点、3=9点。
输出
输出一个最短的移动序列,使得9个时钟的指针都指向12点。按照移动的序号大小,输出结果。
样例输入
3 3 0
2 2 2
2 1 2
样例输出
4 5 8 9
分析
- 从上面的介绍中我们可以看出每次拨动指针转90度,那么有效的拨动数则只能是0、1、2、3,因为比如又再拨动一次就又会重复拨动0次的效果。所以一个移动方案有4种不同的拨动方式,一共有9个移动方案,那么可能的解就有4^9个。
- 此题只要求我们求最小移动的次数,那么在枚举的过程中如果发现当前枚举的情况已超过最小移动次数时则可以直接放弃尝试此解,减少枚举的次数。
实现
#include <iostream>
#include <cstring>
using namespace std;
#define N 9
#define L 9
// a, b, c, d, e, f, g, h, i
int cases[L][N] = {{1, 1, 0, 1, 1, 0, 0, 0, 0}
,{1, 1, 1, 0, 0, 0, 0, 0, 0}
,{0, 1, 1, 0, 1, 1, 0, 0, 0}
,{1, 0, 0, 1, 0, 0, 1, 0, 0}
,{0, 1, 0, 1, 1, 1, 0, 1, 0}
,{0, 0, 1, 0, 0, 1, 0, 0, 1}
,{0, 0, 0, 1, 1, 0, 1, 1, 0}
,{0, 0, 0, 0, 0, 0, 1, 1, 1}
,{0, 0, 0, 0, 1, 1, 0, 1, 1}};
int a[N];
int minCount = 4 * L + 1;
int result[L];
void guess(int (&count)[L], int l, int currentCount){
//枚举到的方案大于minCount时直接放弃
if (currentCount > minCount) {
return;
}
if (l == L) {
int j;
for(j = 0; j < N; j++) {
//检测第j个时钟是否满足指向12点的要求
int sum = a[j];
for(int ll = 0; ll < L; ll++) {
sum += count[ll] * cases[ll][j];
}
if (sum % 4 != 0) {
break;
}
}
if (j == N) {
if (currentCount < minCount) {
minCount = currentCount;
memcpy(result, count, sizeof(count));
}
}
return;
}
int nextLine = l + 1;
for(count[l] = 0; count[l] < 4; count[l]++) {
guess(count, nextLine, currentCount + count[l]);
}
}
int main()
{
// freopen("in.txt", "r", stdin);
memset(result, 0, sizeof(result));
bool isResult = true;
for (int i = 0; i < N; i++) {
cin >> a[i];
if (a[i] % 4 != 0) {
isResult = false;
}
}
if (isResult) {
return 0;
}
//记录采取方案的次数
int count[L];
guess(count, 0, 0);
for(int i = 0; i < L; i++) {
for(int j = 0; j < result[i]; j++) {
cout << i + 1 << " ";
}
}
return 0;
}