❓ The question first
❓ THE QUESTION
Problem — Snail Path
A snail starts on an infinite grid of squares. You are given N moves; each move is a direction letter (N, S, E, W) followed by a positive integer (at most 20) — how many squares to crawl that way. Every square the snail enters becomes slimy, including the starting square. Output T: the number of times the snail enters a square that is already slimy.
Input
First line: N. Then N lines, one move each, like S2.
3 S2 N2 S3
Output
One integer: T, the number of re-entries.
4
🎬 The solution, step by step
The idea — a set, and single steps:
- Keep a set of visited (r, c) squares — the grid is infinite, so no list-of-lists can hold it; a set of pairs can.
- Split every move into single squares: a move like S3 is three separate steps, and each step is checked on its own.
- Each step: if the new square is already in the set,
T += 1; otherwise add it. The start square goes into the set before the first move.
Animation — walk the official sample
💻 The code
N = int(input())
moves = {'N': (-1, 0), 'S': (1, 0), 'E': (0, 1), 'W': (0, -1)}
r = 0
c = 0
visited = {(0, 0)} # the start square is ALREADY slimy
T = 0
for _ in range(N):
move = input().strip()
dr, dc = moves[move[0]] # first character: direction
steps = int(move[1:]) # the rest: how many squares (can be 2 digits!)
for _ in range(steps): # ONE square at a time
r += dr
c += dc
if (r, c) in visited:
T += 1
else:
visited.add((r, c))
print(T)
⭐ Key points & traps
Trap 1 — jumping whole moves: adding S3 as one leap to (r+3, c) skips the squares in between — but the snail slimed them, and re-entries can happen mid-move. Always loop square by square.
Trap 2 — forgetting the start square: without
visited = {(0, 0)}, Sample 1 prints 3 instead of 4. When a sample disagrees by exactly the start, this is why.Parsing: the count can be two digits (
W15), so split as move[0] and int(move[1:]) — never assume one digit.Why a set: coordinates can go negative and up to hundreds in any direction;
(r, c) in visited stays fast no matter how far the snail wanders.✋ Your turn — predict first, then check
Moves: 2 / E2 / W2 — what is T?
East: (0,1) new, (0,2) new. West: (0,1) re-entry ①, (0,0) re-entry ② (the start!). T = 2.