华为机试真题Java 实现【无向图染色】【2022.11 Q4】

题目描述

给一个无向图染色,可以填红黑两种颜色,必须保证相邻两个节点不能同时为红色,输出有多少种不同的染色方案?

输入描述:

第一行输入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);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值