25-cxsj-final/backend/problems/flower_planting/solvers.py

77 lines
2.3 KiB
Python

from typing import List
def solve_greedy(flowerbed: List[int], n: int) -> bool:
"""
Greedy algorithm: Plant whenever possible.
O(N)
"""
count = 0
# Operate on a copy to avoid modifying input in place if passed by reference
bed = flowerbed[:]
length = len(bed)
for i in range(length):
if bed[i] == 0:
empty_left = (i == 0) or (bed[i-1] == 0)
empty_right = (i == length - 1) or (bed[i+1] == 0)
if empty_left and empty_right:
bed[i] = 1
count += 1
if count >= n:
return True
return count >= n
def solve_brute_force(flowerbed: List[int], n: int) -> bool:
"""
Backtracking/Brute Force to see if N flowers can be planted.
O(2^N) - Highly inefficient, good for contrast.
"""
length = len(flowerbed)
def can_plant(bed, index, remaining):
if remaining == 0:
return True
if index >= length:
return False
# Try planting at index
if bed[index] == 0:
empty_left = (index == 0) or (bed[index-1] == 0)
empty_right = (index == length - 1) or (bed[index+1] == 0)
if empty_left and empty_right:
# Option 1: Plant here
bed[index] = 1
if can_plant(bed, index + 2, remaining - 1):
return True
bed[index] = 0 # Backtrack
# Option 2: Don't plant here, try next spot
if can_plant(bed, index + 1, remaining):
return True
return False
# Safety for large inputs
if length > 25:
# Fallback
return solve_greedy(flowerbed, n)
return can_plant(flowerbed[:], 0, n)
# Helper for just counting max flowers (often the core logic needed)
def max_flowers_greedy(flowerbed: List[int]) -> int:
count = 0
bed = flowerbed[:]
length = len(bed)
for i in range(length):
if bed[i] == 0:
empty_left = (i == 0) or (bed[i-1] == 0)
empty_right = (i == length - 1) or (bed[i+1] == 0)
if empty_left and empty_right:
bed[i] = 1
count += 1
return count