Skip to content

Commit 6090b69

Browse files
authored
Branch 1 (#3)
* 1513 * Upload: "Flower Planting with No adjacent"-Python
1 parent ffc7ed3 commit 6090b69

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Diff for: Python/1042_FlowerPlantingwithNoAdjacent.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#Difficulty = Medium
2+
#Submission Speed = 85.81%
3+
'''
4+
#The Algorithm is similar to Graph coloring algorithm.
5+
After making the graph from edge lists,
6+
We will traverse every node one by one. For every node, create a fresh new list of choices of flowers
7+
While Traversing a particular node (say NODE A), we will check its neighbours and if any of the neighbour has been assigned
8+
flower (say flower 'X') we will remove that flower ('X') from the list of choices of the corresponding Node (NODE A)
9+
'''
10+
'''
11+
If E = Number of Edges
12+
V = Number of Vertices/Nodes
13+
Time Complexity = O(V+E)
14+
Space Complexity = O(2V+E)
15+
'''
16+
from collections import defaultdict
17+
class Solution:
18+
def gardenNoAdj(self, N, paths):
19+
20+
#Create Graph
21+
graph = defaultdict(list)
22+
for i in paths:
23+
graph[i[0]].append(i[1]) #Since Graph is Bidirectional, we need to add edge both sides
24+
graph[i[1]].append(i[0])
25+
flowers = []
26+
for i in range(1, N + 1): #We will traverse every node one by one
27+
choice = [1, 2, 3, 4] #create a fresh new list of choices of flowers
28+
for k in graph[i]: #check its neighbours
29+
try:
30+
choice.remove(flowers[k-1]) #if any of the neighbour has been assigned flower (say flower 'X') we will remove that flower ('X')
31+
except:
32+
pass
33+
flowers.append(choice[0]) #Select the first flower from the remaining choices
34+
return flowers

Diff for: README.md

+10
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,16 @@ This repository consists of the solutions of the problems from LeetCode platform
9595
| # | Title | Solution | Time | Space | Difficulty | Tag | Note|
9696
|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----|
9797

98+
<br/>
99+
<div align="right">
100+
<b><a href="#algorithms">⬆️ Back to Top</a></b>
101+
</div>
102+
<br/>
103+
104+
## Graph
105+
| # | Title | Solution | Time | Space | Difficulty | Tag | Note|
106+
|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----|
107+
|1042|[Flower Planting with No Adjacent](https://leetcode.com/problems/flower-planting-with-no-adjacent/)|[Python](./Python/1042_FlowerPlantingwithNoAdjacent.py)|_O(V+E)_|_O(2V+E)_|Medium|Graph|Graph Coloring|
98108

99109

100110
<br/>

0 commit comments

Comments
 (0)