【leetcode】1042. Flower Planting With No Adjacent

博客围绕花园种花问题展开,题目要求为多个花园选种花类型,使相连花园花不同。解题思路是,因可供选花仅四种,对每个待种植花园,判断相邻花园已种花卉,从可选列表去除,在剩余种类中任选一个。还给出了代码来源。

题目如下:

You have N gardens, labelled 1 to N.  In each garden, you want to plant one of 4 types of flowers.

paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.

Also, there is no garden that has more than 3 paths coming into or leaving it.

Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.

Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden.  The flower types are denoted 123, or 4.  It is guaranteed an answer exists.

 

Example 1:

Input: N = 3, paths = [[1,2],[2,3],[3,1]]
Output: [1,2,3]

Example 2:

Input: N = 4, paths = [[1,2],[3,4]]
Output: [1,2,1,2]

Example 3:

Input: N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
Output: [1,2,3,4]

 

Note:

  • 1 <= N <= 10000
  • 0 <= paths.size <= 20000
  • No garden has 4 or more paths coming into or leaving it.
  • It is guaranteed an answer exists.

解题思路:可供选的花的种类只有[1,2,3,4]四种,对于任意一个待种植的花园,只需要判断相邻的花园是否已经种植花卉。如果种植了,把已种植的种类从可供选择的列表中去除,最后在剩余的种类中任选一个即可。

代码如下:

class Solution(object):
    def gardenNoAdj(self, N, paths):
        """
        :type N: int
        :type paths: List[List[int]]
        :rtype: List[int]
        """
        res = [0] * (N+1)
        res[1] = 1
        dic = {}
        for v1,v2 in paths:
            dic[v1] = dic.setdefault(v1,[]) + [v2]
            dic[v2] = dic.setdefault(v2,[]) + [v1]
        for i in range(2,N+1):
            if i not in dic:
                res[i] = 1
            else:
                choice = [1,2,3,4]
                for neibour in dic[i]:
                    if res[neibour] == 0:
                        continue
                    else:
                        if res[neibour] in choice:
                            inx =  choice.index(res[neibour])
                            del choice[inx]
                res[i] = choice[0]
        return res[1:]

 

转载于:https://www.cnblogs.com/seyjs/p/10904685.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值