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
- Level: Junior J5
- Pattern: Flood Fill, Grid BFS/DFS, Connected Component Accumulation
- Prerequisite: 2D lists/grids, queues or recursion, visited arrays, four-direction movement, running totals
- What this teaches: When a problem asks for the whole reachable region, find the connected component instead of one shortest path.
- Where it appears again: grid graph traversal, connected components, multi-source BFS, region scoring
What to Study Next
- Related CP Weekly problems: CCC 2026 J4 Snail Path for grid simulation, CCC 2023 J4/S1 Trianglane for grid adjacency, CCC 2020 J5/S2 Escape Room for implicit graph BFS.
- Related Python / C++ foundations: 2D lists/vectors, deque/queue, visited arrays, loops and boundary checks, running totals.
- Related DSA roadmap article: CCC Grid Problems: from simulation to graph search (planned).
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
- Solving it as a shortest-path problem instead of a connected-component sum.
- Forgetting to use
visited. - Marking cells as visited too late, which can allow duplicate queue entries.
- Subtracting 1 from the starting coordinates even though they are already zero-indexed.
- Allowing diagonal movement.
- Walking through
*hay bales. - Using recursive DFS in Python on a large grid and hitting recursion limits.
Review Questions
- Why is this problem a flood fill problem?
- Why should a cell be marked visited when it is added to the queue?
- Why is every reachable cell counted exactly once?
- Why are pumpkins in other separated regions not included?
- Why is BFS usually safer than recursive DFS in Python for this problem?
Questions or feedback?
Have a question about this article or want to suggest an improvement? Send us an email.
