【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:]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM