12.展会彩灯 早些年,在展会上可能会看到这样一种彩灯:一个被连接到若干开关上的电灯泡,只当所有开关闭合的时候才会发光。每一个开关由一个按钮控制;按下按钮就会切换开关状态,但是开关的状态是无法知道的。目标就是点亮灯泡。设计一个点亮灯泡的算法,使其在有你n个开关时,在最坏的情况下,需要按动按钮的次数最少。
public static int[][] results;
public static int temp;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
temp = n; // 辅助记录切割数组
int m = (int) Math.pow(2, n);
results = new int[m][n];
func(m, n);
// 打印二维数组
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(results[i][j] + " ");
}
System.out.println();
}
}
public static void func(int row, int col) {
if (col == 1) {
// 填写第二行最后一个值
results[row - 1][results[0].length - 1] = 1;
} else {
func(row / 2, col - 1);
for (int i = 0; i < row / 2; i++) {
// 填写当前切割数组快的results后n/2行的首列数值
// temp用于辅助找出被切割数组的第一列
results[row / 2 + i][temp - col] = 1;
for (int j = 1; j < col; j++) {
// 复制切割数组results内部的n/2上部分到下部分
results[row - i - 1][results[0].length - j] = results[i][results[0].length - j];
}
}
}
}