首页 > 其他 > 详细

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

时间:2020-07-23 16:44:37      阅读:79      评论:0      收藏:0      [点我收藏+]

问题描述

有 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;
    }
}

 

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

原文:https://www.cnblogs.com/xxxxxiaochuan/p/13365833.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!