Accel Thinking

CP Weekly Challenges

CCC 2024 J5 Harvest Waterloo Solution: Flood Fill and Grid BFS

Learn how to solve CCC 2024 J5 Harvest Waterloo with flood fill, BFS, connected components, and grid accumulation in Python and C++.

This problem is set in a pumpkin patch, but algorithmically it is a classic flood fill problem. We are not looking for one path to one destination. We are looking for the entire connected region that the farmer can reach from the starting cell.

Once we visit every reachable pumpkin cell, we add up the values of those pumpkins.

Where This Fits in the CCC DSA Map

What to Study Next

What the Problem Is Asking

We are given an R x C grid. Each cell contains one of four characters:

S = small pumpkin, value 1
M = medium pumpkin, value 5
L = large pumpkin, value 10
* = bale of hay, blocked

The farmer starts at row A and column B. The top-left corner is (0, 0), so the input coordinates are already zero-indexed.

The farmer may move up, down, left, or right. The farmer cannot move diagonally, move outside the grid, or move through a bale of hay.

The output is the total value of all pumpkins reachable from the starting position.

Where Beginners Often Get Stuck

The first common mistake is thinking there must be a target cell. There is no exit to reach in this problem. We need the total value of the whole reachable component.

The second common mistake is not using visited. Without it, neighboring cells can keep adding each other back into the queue.

The third common mistake is indexing. The starting row and column are already zero-indexed, so we should not subtract one.

Core Algorithm Idea

Treat the grid as a graph:

each non-* cell = node
4-direction adjacency = edge

Starting from (A, B), we run BFS to visit every node in the same connected component. Whenever we process a cell, we add its pumpkin value to the answer.

BFS and DFS both work. BFS with a queue is often safer in Python because it avoids recursion-depth problems on large grids.

Python Solution

from collections import deque

R = int(input())
C = int(input())

patch = [list(input().strip()) for _ in range(R)]

A = int(input())
B = int(input())

value = {
    "S": 1,
    "M": 5,
    "L": 10,
}

directions = [
    (1, 0),
    (-1, 0),
    (0, 1),
    (0, -1),
]

visited = [[False] * C for _ in range(R)]
q = deque()

visited[A][B] = True
q.append((A, B))

total = 0

while q:
    r, c = q.popleft()

    total += value[patch[r][c]]

    for dr, dc in directions:
        nr = r + dr
        nc = c + dc

        if nr < 0 or nr >= R or nc < 0 or nc >= C:
            continue

        if patch[nr][nc] == "*":
            continue

        if visited[nr][nc]:
            continue

        visited[nr][nc] = True
        q.append((nr, nc))

print(total)

C++ Solution

#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int R, C;
    cin >> R >> C;

    vector<string> patch(R);
    for (int r = 0; r < R; r++) {
        cin >> patch[r];
    }

    int A, B;
    cin >> A >> B;

    vector<vector<bool>> visited(R, vector<bool>(C, false));
    queue<pair<int, int>> q;

    visited[A][B] = true;
    q.push({A, B});

    int total = 0;

    int dr[4] = {1, -1, 0, 0};
    int dc[4] = {0, 0, 1, -1};

    while (!q.empty()) {
        auto [r, c] = q.front();
        q.pop();

        if (patch[r][c] == 'S') total += 1;
        else if (patch[r][c] == 'M') total += 5;
        else if (patch[r][c] == 'L') total += 10;

        for (int k = 0; k < 4; k++) {
            int nr = r + dr[k];
            int nc = c + dc[k];

            if (nr < 0 || nr >= R || nc < 0 || nc >= C) {
                continue;
            }

            if (patch[nr][nc] == '*') {
                continue;
            }

            if (visited[nr][nc]) {
                continue;
            }

            visited[nr][nc] = true;
            q.push({nr, nc});
        }
    }

    cout << total << "\n";
    return 0;
}

Complexity Analysis

Each grid cell is added to the queue at most once. For each cell, we check four neighbors.

The time complexity is:

O(RC)

The memory complexity is also:

O(RC)

This fits the official bound R * C <= 100000.

Common Mistakes

  1. Solving it as a shortest-path problem instead of a connected-component sum.
  2. Forgetting to use visited .
  3. Marking cells as visited too late, which can allow duplicate queue entries.
  4. Subtracting 1 from the starting coordinates even though they are already zero-indexed.
  5. Allowing diagonal movement.
  6. Walking through * hay bales.
  7. Using recursive DFS in Python on a large grid and hitting recursion limits.

Review Questions

  1. Why is this problem a flood fill problem?
  2. Why should a cell be marked visited when it is added to the queue?
  3. Why is every reachable cell counted exactly once?
  4. Why are pumpkins in other separated regions not included?
  5. Why is BFS usually safer than recursive DFS in Python for this problem?