中級 0件解決済み 正答率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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。