码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode1042 Flower Planting With No Adjacent

时间:2020-02-03 22:04:46      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:connected   leetcode   span   belle   elf   nal   出现   out   算法   

 1 """
 2 You have N gardens, labelled 1 to N.  In each garden, you want to plant one of 4 types of flowers.
 3 paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
 4 Also, there is no garden that has more than 3 paths coming into or leaving it.
 5 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.
 6 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 1, 2, 3, or 4.  It is guaranteed an answer exists.
 7 Example 1:
 8 Input: N = 3, paths = [[1,2],[2,3],[3,1]]
 9 Output: [1,2,3]
10 Example 2:
11 Input: N = 4, paths = [[1,2],[3,4]]
12 Output: [1,2,1,2]
13 Example 3:
14 Input: N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
15 Output: [1,2,3,4]
16 """
17 """
18 此题用贪心算法
19 没掌握
20 """
21 class Solution(object):
22     def gardenNoAdj(self, N, paths):
23         res = [0] * N
24         m = [[] for i in range(N + 1)]  # 用来存第i个结点到其他结点的路径,i为1到N
25         for x, y in paths:
26             m[x].append(y)
27             m[y].append(x)
28         for i in range(1, N + 1):  # 对N个路径进行遍历
29             used = set()  # 用来存这个结点出现的所有路径使用过的颜色
30             for j in m[i]:
31                 used.add(res[j - 1])  # 把目的地的颜色放入used里
32             for j in range(1, 5):  # 1,2,3,4代表四种颜色
33                 if j not in used:
34                     res[i - 1] = j  # 将该结点存入新的颜色
35                     break
36         return res

 

leetcode1042 Flower Planting With No Adjacent

标签:connected   leetcode   span   belle   elf   nal   出现   out   算法   

原文地址:https://www.cnblogs.com/yawenw/p/12257560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!