Snake
InterviewTime limit1sMemory limit1024 MB
Given a screen of width N and height M filled by a spiral snake with its head at (0, 0), find the length in cells from the head to body cell (X, Y).
- Level
Medium4 of 10
- Topics
- Math, Implementation
- Solved
- No attempts yet
Problem
Mantas likes to play the classic Snake game. The idea is simple: eat apples, grow the snake, and keep its head from hitting its body.
Once, Mantas won the game. The snake lies in a spiral shape, as shown in the picture, and fills every cell of the screen.
Let the head of the snake be at coordinate (0; 0). Given the screen width N and height M, find the length of the snake from the head to the body cell (X; Y).

Figure 1. For N = 6 and M = 6, the length from the head to X = 2, Y = 4 is 28.
Coordinates increase to the right and downward. The length is counted in cells, from the center of the head cell to the center of the given body cell.