Back to Solutions

Number Spiral

Explanation

In this problem, we are given a grid with a specific pattern and we need to identify the element in the cell (x, y).

Here, the first row follows this pattern:

haskell 1 2 9 10 25 ... +1 +7 +1 +15 ...

The difference between adjacent elements in the first row alternates between 1 and 7 + (8 * (n / 2 - 1)), where n is the row number.

Similarly, the different between adjacent elements in the first column alternates between 3 + (8 * (n / 2 - 1)) and 1, where n is the column number.

As you may have noticed, moving down the first row it adds 1 to the number if the row number is even, otherwise it subtracts 1. This pattern follows until the column number is greater than the row number.

Similary, moving right from the first column, it adds 1 to the number if the column number is odd, otherwise it subtracts 1.

After finding ith element of the first row, we can just move down the column and find the jth element of the ith row, as long as j is less than i. Otherwise, we'll find the jth element of the first column and move right to find the ith element of the jth column.

Code

for _ in range(int(input())):
    y, x = map(int, input().split())

    if x >= y:
        # calculate the xth element of the first row
        n = (x - 1) // 2
        first = 1 + x // 2 + (7 * ((x - 1) // 2)) + (8 * (n * (n - 1)) // 2)

        ans = first + ((y - 1) if x % 2 == 0 else (1 - y))
    else:
        # calculate the yth element of the first column
        n = (y // 2) - 1
        first = 1 + (y - 1) // 2 + (3 * (y // 2)) + (8 * (n * (n + 1)) // 2)

        ans = first + ((x - 1) if y % 2 == 1 else (1 - x))

    print(ans)