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 1, 2, 3, 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.
思路:如下的BFS会WA,因为可能出现某个位置无法被放入(会被强制弄成1,即:res[i]=1),比如下面这种情况,中间这个方块形状的点就无法填入合理的node,出现这种的原因在于:一次性考虑的点太多了,比如下面这种情况为什么会出现呢?
因为在填标记为3号点的周围点的时候,比如现在要填的就是方块形状的点,我们一方面要考虑3号点 和 3号点周围其他点(1,2),也要考虑方块形状点的周围其他点(1,4)
class Solution(object):
def gardenNoAdj(self, N, paths):
"""
:type N: int
:type paths: List[List[int]]
:rtype: List[int]
"""
adj=[set() for _ in range(N+1)]
for s,t in paths:
adj[s].add(t)
adj[t].add(s)
res=[-1]*(N+1)
for i in range(1,N+1):
if res[i]!=-1: continue
res[i]=1
q=[i]
while q:
s=q.pop()
used=set([res[s]]+[res[t] for t in adj[s] if res[t]!=-1])
for t in adj[s]:
if res[t]!=-1: continue
for k in range(1,5):
if k in used: continue
if k in [res[tt] for tt in adj[t] if res[tt]!=-1]: continue
res[t]=k
used.add(k)
q.append(t)
break
return res[1:]
s=Solution()
print(s.gardenNoAdj(5, [[3,4],[4,5],[3,2],[5,1],[1,3],[4,2]]))
print(s.gardenNoAdj(N = 3, paths = [[1,2],[2,3],[3,1]]))
print(s.gardenNoAdj(N = 4, paths = [[1,2],[3,4]]))
print(s.gardenNoAdj(N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]))
其实,想复杂了,因为每个点连接边数最多3个,所以每个点一定能找到一个合理的数字填进去,所以每次只需要focus在一个点的周围就好了,
class Solution(object):
def gardenNoAdj(self, N, paths):
"""
:type N: int
:type paths: List[List[int]]
:rtype: List[int]
"""
adj=[set() for _ in range(N+1)]
for s,t in paths:
adj[s].add(t)
adj[t].add(s)
res=[-1]*(N+1)
for i in range(1,N+1):
res[i] = ({1,2,3,4}-{res[j] for j in adj[i]}).pop()
return res[1:]