Problem solution · Python

CCC 2024 J5 - Harvest Waterloo

CCC 2024 J5 - Harvest Waterloo: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to CCCSolutions.

Technique
Breadth-first search
Source
CCCSolutions
Length
60 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For CCC 2024 J5 - Harvest Waterloo, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 60 lines of Python from the credited upstream file ccc24j5.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from CCCSolutions by CCCSolutions contributors · Milliken Mills High School and is used under the MIT licence.

Full codeCCC 2024 J5 - Harvest Waterloo · PythonPython
Use this to learn the idea, then write your own version.
# By Daniel Zhang, Pinetree Secondary from collections import deque r = int(input())c = int(input())  def valid(node):    x, y = node    if 0 <= x < r:        if 0 <= y < c:            if not vis[x][y]:                if patch[x][y] != "*":                    return True    return False def neighbours(node):    x, y = node    return [[x+1, y], [x-1, y], [x, y+1], [x, y-1]] patch = []vis = [] for i in range(r):    patch.append(list(input()))    vis.append([False] * c) a = int(input())b = int(input()) queue = deque([[a, b]])score = 0vis[a][b] = Truecur = patch[a][b]if cur == "S":    score += 1if cur == "M":    score += 5if cur == "L":    score += 10    while queue:    node = queue.popleft()        for n in neighbours(node):        if valid(n):            a, b = n[0], n[1]            vis[a][b] = True            cur = patch[a][b]            if cur == "S":                score += 1            if cur == "M":                score += 5            if cur == "L":                score += 10             queue.append(n) print(score)

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗