题解思路来源于:费解的开关 https://www.acwing.com/file_system/file/content/whole/index/content/3646/
相关题解: https://acwing.com/file_system/file/content/whole/index/content/12664204/
枚举16个开关的所有状态(用二进制数来表示)求解最小值即可
import java.io.*;
import java.util.*;
public class Main {
static char[][] g = new char[6][6];
static ArrayList<int[]> ans = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
for (char i = 1; i <= 4; i++) g[i] = toArr(sc.nextLine().toCharArray());
int cnt = work();
//输出结果
out.println(cnt);
for (int[] item : ans) {
out.println(item[0] + " " + item[1]);
}
out.flush();
}
/**
* 索引从1开始的
* 返回索引u对应的x坐标(一维转二维)
*/
static int getX(int u) {
return (u - 1) / 4 + 1;
}
/**
* 返回索引u对应的y坐标(一维转二维)
*/
static int getY(int u) {
return (u - 1) % 4 + 1;
}
static void turn(int x, int y) {
for (int i = 1; i <= 4; i++) {
if (g[x][i] == '-') g[x][i] = '+';
else g[x][i] = '-';
if (g[i][y] == '-') g[i][y] = '+';
else g[i][y] = '-';
}
if (g[x][y] == '-') g[x][y] = '+';
else g[x][y] = '-';
}
static int work() {
int cnt = 1000000;
for (int k = 0; k < 1 << 16; k++) {
ArrayList<int[]> list = new ArrayList<>();
int res = 0;
char[][] backup = new char[6][6];
for (int i = 1; i <= 4; i++) backup[i] = Arrays.copyOf(g[i], 6);
for (int i = 0; i < 16; i++) {
if ((k >> i & 1) == 1) {
res++;
//由于我的索引从1开始,所以有1的偏移量
int x = getX(i + 1), y = getY(i + 1);
list.add(new int[]{x, y});
turn(x, y);
}
}
boolean flag = true;
for (int i = 1; i <= 4; i++) {
boolean flag2 = false;
for (int j = 1; j <= 4; j++)
if (g[i][j] == '+') {
flag = false;
flag2 = true;
break;
}
if (flag2) break;
}
//不添加等于就符合了题目的要求了
//该枚举方式本来就是自上到下,从左到右
if (flag && res < cnt) {
cnt = res;
ans.clear();
ans.addAll(list);
}
for (int i = 1; i <= 4; i++) g[i] = Arrays.copyOf(backup[i], 6);
}
return cnt;
}
static char[] toArr(char[] str) {
char[] res = new char[6];
for (int i = 1; i <= 4; i++) res[i] = str[i - 1];
return res;
}
}
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla