题目描述
给一个无向图染色,可以填红黑两种颜色,必须保证相邻两个节点不能同时为红色,输出有多少种不同的染色方案?
输入描述:
第一行输入M(图中节点数) N(边数)
后续N行格式为:V1 V2表示一个V1到V2的边。
数据范围:1 <= M <= 15,0 <= N <= M * 3,不能保证所有节点都是连通的。
输出描述:
输出一个数字表示染色方案的个数。
示例1:
输入:
4 4
1 2
2 4
3 4
1 3
输出:
7
说明:4个节点,4条边,1号节点和2号节点相连,2号节点和4号节点相连,3号节点和4号节点相连,1号节点和3号节点相连,若想必须保证相邻两个节点不能同时为红色,总共7种方案。
个人解法
不保证通过率
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
public class Main {
private static int result = 0;
enum MColor {NULL, RED, BLACK}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] inputs0 = br.readLine().split(" ");
int M = Integer.parseInt(inputs0[0]), N = Integer.parseInt(inputs0[1]);
HashMap<Integer, MColor> colors = new HashMap<>();
HashMap<Integer, HashSet<Integer>> map = new HashMap<>();
for (int i = 0; i < N; i++) {
String[] inputs1 = br.readLine().split(" ");
for (int j = 0; j < 2; j++) {
int key = Integer.parseInt(inputs1[j]);
int value = Integer.parseInt(inputs1[1 - j]);
HashSet<Integer> set = map.getOrDefault(key, new HashSet<>());
set.add(value);
map.put(key, set);
colors.put(j, MColor.NULL);
}
}
draw(colors, map, 1);
System.out.println(result);
}
public static void draw(HashMap<Integer, MColor> colors, HashMap<Integer, HashSet<Integer>> map, int times) {
if (times - 1 == map.size()) {
result++;
return;
}
colors.put(times, MColor.BLACK);
draw(colors, map, times + 1);
colors.put(times, MColor.NULL);
int rc = 0;
for (Integer integer : map.get(times)) {
if (colors.get(integer) == MColor.RED) {
rc++;
break;
}
}
if (rc == 0) {
colors.put(times, MColor.RED);
draw(colors, map, times + 1);
colors.put(times, MColor.NULL);
}
}
}