Accel Thinking

CP Weekly Challenges

CCC 2026 J4 - Snail Path Solution & Analysis

Simulate the snail step by step, track slimy squares with a visited set, and count every revisit.

Imagine the snail starts on one grid square. That starting square is already part of its trail, because the problem says the snail makes the squares it touches slimy. In the example “move east 3 squares”, there are 4 slimy squares total, which includes the starting square.

本题在 CCC DSA 地图里的位置

下一步推荐

Where This Fits in the CCC DSA Map

What to Study Next

Understanding the Problem

Every time the snail moves one square, we check whether the new square was already slimy.

So the problem is really asking: as the snail walks step by step, how many times does it revisit an old square?

Important Detail Students Often Miss

A movement like S2 does not mean one big jump. It means move 1 square south, then move 1 more square south.

You must process movements one square at a time, because the snail could enter an already slimy square in the middle of a longer movement. The movement format is a direction letter followed by a positive integer up to 20.

Core DSA Concepts

Coordinate Updates

Big Idea

Start from the original square and add it to a visited set. For each movement command, repeat the movement one square at a time. After each single step, check whether the new coordinate is already in the set. If it is, increase the revisit count. Then add the coordinate to the set.

Python Solution

# CCC 2026 J4 - Snail Path
# Read the number of movements
M = int(input())

# Current position of the snail
x = 0
y = 0

# The starting square is already touched, so it is slimy
visited = set()
visited.add((x, y))

# Count how many times the snail enters a square
# that was already slimy
answer = 0

# Direction changes for one step
dx = {
    "E": 1,
    "W": -1,
    "N": 0,
    "S": 0
}

dy = {
    "E": 0,
    "W": 0,
    "N": 1,
    "S": -1
}

# Process each movement
for _ in range(M):
    move = input().strip()

    # First character is the direction
    direction = move[0]

    # The rest of the string is the distance
    distance = int(move[1:])

    # Move one square at a time
    for _ in range(distance):
        x += dx[direction]
        y += dy[direction]

        if (x, y) in visited:
            answer += 1

        visited.add((x, y))

print(answer)

Common Mistakes