Skip to content

Commit 5ad9a80

Browse files
committed
Added medium problem.
1 parent 1197f44 commit 5ad9a80

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
# FLOWER PLANTING WITH NO ADJACENT
3+
4+
You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.
5+
6+
All gardens have at most 3 paths coming into or leaving it.
7+
8+
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.
9+
10+
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.
11+
12+
Example 1:
13+
14+
Input: n = 3, paths = [[1,2],[2,3],[3,1]]
15+
Output: [1,2,3]
16+
Explanation:
17+
Gardens 1 and 2 have different types.
18+
Gardens 2 and 3 have different types.
19+
Gardens 3 and 1 have different types.
20+
Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].
21+
22+
Example 2:
23+
24+
Input: n = 4, paths = [[1,2],[3,4]]
25+
Output: [1,2,1,2]
26+
27+
Example 3:
28+
29+
Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
30+
Output: [1,2,3,4]
31+
32+
Constraints:
33+
34+
1 <= n <= 104
35+
0 <= paths.length <= 2 * 104
36+
paths[i].length == 2
37+
1 <= xi, yi <= n
38+
xi != yi
39+
Every garden has at most 3 paths coming into or leaving it.
40+
"""
41+
42+
class Solution:
43+
def gardenNoAdj(self, n: int, paths):
44+
graph = [[] for i in range(n)]
45+
for start, end in paths:
46+
graph[start - 1].append(end - 1)
47+
graph[end - 1].append(start - 1)
48+
49+
flowers = [None for i in range(n)]
50+
51+
visited = set()
52+
for garden in range(n):
53+
if garden not in visited:
54+
self.bfs(graph, garden, flowers, visited)
55+
56+
return flowers
57+
58+
def bfs(self, graph, current, flowers, visited):
59+
queue = [current]
60+
while len(queue) != 0:
61+
tempQueue = []
62+
for garden in queue:
63+
visited.add(garden)
64+
flowers[garden] = self.assignFlower(graph, garden, flowers)
65+
for neighbor in graph[garden]:
66+
if neighbor in visited:
67+
continue
68+
tempQueue.append(neighbor)
69+
queue = tempQueue
70+
71+
def assignFlower(self, graph, current, flowers):
72+
for flower in range(1, 5):
73+
found = True
74+
for neighbor in graph[current]:
75+
if flowers[neighbor] == flower:
76+
found = False
77+
break
78+
if found:
79+
return flower

0 commit comments

Comments
 (0)