• 1042. 不邻接植花-无向图-简单


    问题描述

    有 N 个花园,按从 1 到 N 标记。在每个花园中,你打算种下四种花之一。

    paths[i] = [x, y] 描述了花园 x 到花园 y 的双向路径。

    另外,没有花园有 3 条以上的路径可以进入或者离开。

    你需要为每个花园选择一种花,使得通过路径相连的任何两个花园中的花的种类互不相同。

    以数组形式返回选择的方案作为答案 answer,其中 answer[i] 为在第 (i+1) 个花园中种植的花的种类。花的种类用  1, 2, 3, 4 表示。保证存在答案。

    示例 1:

    输入:N = 3, paths = [[1,2],[2,3],[3,1]]
    输出:[1,2,3]
    示例 2:

    输入:N = 4, paths = [[1,2],[3,4]]
    输出:[1,2,1,2]
    示例 3:

    输入:N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
    输出:[1,2,3,4]
     

    提示:

    1 <= N <= 10000
    0 <= paths.size <= 20000
    不存在花园有 4 条或者更多路径可以进入或离开。
    保证存在答案。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/flower-planting-with-no-adjacent

    解答

    class Solution {
        Map<Integer,List<Integer>> graph;
        Map<Integer,Integer> flower;
        public int[] gardenNoAdj(int N, int[][] paths) {
            graph = new HashMap<Integer,List<Integer>>();
            flower = new HashMap<Integer,Integer>();
            List<Integer> available = new LinkedList<Integer>();
            available.add(1);
            available.add(2);
            available.add(3);
            available.add(4);
    
            int i;
            for(i=1;i<=N;i++){
                graph.put(i,new ArrayList<Integer>());
                flower.put(i,0);
            }
            //构造graph
            for(int[] temp:paths){
                graph.get(temp[0]).add(temp[1]);
                graph.get(temp[1]).add(temp[0]);
            }
    
            for(int p:graph.keySet()){
                if(flower.get(p)==0){
                    List<Integer> temp = new LinkedList<Integer>(available);
                    for(int j:graph.get(p)){//移除可用的花
                        if(flower.get(j)!=0)temp.remove(new Integer(flower.get(j)));
                    }
                    flower.put(p,temp.get(0));
                }
            }
            int[] res = new int[N];
            i = 0;
            for(int p:flower.values()){
                res[i] = p;
                i++;
            }
            return res;
        }
    }
  • 相关阅读:
    global s power in php...
    null is empty
    如何创建spring web 工程
    如何下载spring sts
    使用apache-commons-lang3架构对HTML内容进行编码和反编码
    SQL 查询建表SQL
    kindeditor 在JSP 中上传文件的配置
    在java web工程中jsp页面中使用kindeditor
    实现<base>标签中有绝对路径
    实现多个JSP页面共用一个菜单
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13365833.html
Copyright © 2020-2023  润新知