• leetcode1042 Flower Planting With No Adjacent


     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
  • 相关阅读:
    zookeeper安装教程
    CentOS7服务管理(重启,停止,自动启动命令)
    redis配置文件详解
    阿里云 CentOS7安装redis4.0.9并开启远程访问
    rpm命令
    wget命令
    yum命令
    maven项目debug调试不能够进入源码问题解决
    8-字符串
    7-数组
  • 原文地址:https://www.cnblogs.com/yawenw/p/12257560.html
Copyright © 2020-2023  润新知