모든 챌린지
보통 1명 해결 정답률 100.0%

Number Spiral Lookup

Find a value by row and column in an expanding number spiral.

배우게 될 내용

  • Find a formula in a number pattern
  • Split the problem by layer and parity
  • Use 64-bit integers for large values

문제

번역본 보기

The infinite spiral starts at the top-left cell. The first four rows and columns are shown below. Continue the same pattern in expanding square layers. Coordinates start at 1.

 1   2   9  10
 4   3   8  11
 5   6   7  12
16  15  14  13

Return one cell value without constructing the entire grid.

Implement number_spiral(row, column).

Input

row: The row counted from the top, starting at 1.

column: The column counted from the left, starting at 1.

Output

Return the number at that position.

제약 조건

1 ≤ row, column ≤ 1,000,000,000. The value fits a signed 64-bit integer.

예시

예시 1
입력:
row = 3
column = 2

예상 출력:
expected = 6
입력:
long long row = 3;
long long column = 2;

예상 출력:
long long expected = 6;
입력:
long row = 3;
long column = 2;

예상 출력:
long expected = 6;

설명

In the displayed third row, the second value is 6.

예시 2
입력:
row = 1
column = 4

예상 출력:
expected = 10
입력:
long long row = 1;
long long column = 4;

예상 출력:
long long expected = 10;
입력:
long row = 1;
long column = 4;

예상 출력:
long expected = 10;

설명

The fourth square layer begins at 10 in the top row.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

The spiral is built in square layers, so a cell belongs to a layer determined by the larger coordinate.

힌트 2

Use the parity of that layer to decide whether values increase along a row or a column.

힌트 3

Pay attention to whether the layer reaches from the top-left corner or the opposite corner first.

예상 복잡도

O(1) time, O(1) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 ННикита Python 986 ms - 5/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 솔루션

스포일러: 아래에 1개 전체 솔루션 있음 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.