# Problem Description
This is a matrix traversal problem where we need to:
- Create a 4n × 4n matrix filled with consecutive integers starting from 1 to 16n²
- Follow a specific green path pattern starting from a calculated position
- Return the sequence of numbers encountered along this path
- The path always ends at position 1 (top-left corner)

# Visual Facts
1. Matrix Structure:
   - N=1: 4×4 matrix with numbers 1-16
   - N=2: 8×8 matrix with numbers 1-64
   - Numbers arranged sequentially in row-major order

2. Path Examples:
   - N=1 path: [7,11,15,14,13,9,5,1]
   - N=2 path: [29,37,45,44,43,35,27,19,11,12,13,14,15,23,31,39,47,55,63,62,61,60,59,58,57,49,41,33,25,17,9,1]

3. Starting Positions:
   - N=1 starts at 7 (row 2, col 3) (1-indexed)
   - N=2 starts at 29 (row 4, col 5) (1-indexed)


# Visual Patterns
1. Matrix Size Rule:
   - Size = 4n × 4n
   - Total elements = 16n²

2. Starting Position Pattern:
   - Start row = 4n/2 - 1 = 2n-1 (0-indexed)
   - Start column = (4n/2) = 2n (1-indexed)

3. Path Movement Rules:
   - Follows a clockwise spiral pattern
   - Movement alternates between:
     * Down, left, up, right, down, left, up, right, ...
   - Initial step size = 2
     * Step size increases by 2 every two border encounters
     * The step size for the first moving down and then moving left is 2
     * The step size for the next moving up and then moving right is 4
     * The step size for the next moving down and then moving left is 6
     * The step size for the next moving up and then moving right is 8
     * And so on...
   - Every time after path moving left or right, the step size + 2.
      e.g. starting from (2n-1,2n), the path visit: (2n-1,2n)->(2n+1,2n) (moving down 2 steps), (2n+1,2n)->(2n+1,2n-2) (moving left 2 steps), (2n+1,2n-1)->(2n-3,2n-1)(moving up 4 steps) …… repeat until it moving inward to (1,1)
      The path moves 1 step every time, so all the number visited on its way should be outputed.

4. Termination:
   - Always ends at position 1 (top-left corner)
   - Path gradually works its way to the outside of the matrix before moving inward to position 1

# Solution
from typing import List

def solution(n: int) -> List[int]:
    """
    Traverses a 4n x 4n matrix following a specified green path and returns the values encountered.

    Parameters:
        n (int): Integer that determines the matrix dimensions (4n x 4n).

    Returns:
        List[int]: List of values encountered while traversing the green path.
    """
    mat = lambda i, j : 4 * n * i + j + 1
    answer = []
            
    def getAns(i,j, direction, ans):
        ans.append(mat(i,j))
        step = 2
        while 0 <= i < 4*n and 0 <= j < 4*n:
            temp = 1
            while temp <= step:
                # 0->up, 1-> right, 2-> down, 3-> left
                if direction == 0:
                    i = i - 1
                elif direction == 1:
                    j = j + 1
                elif direction == 2:
                    i = i + 1
                else:
                    j = j - 1
                ans.append(mat(i,j))   
                temp += 1
            direction = (direction + 1)%4
            if direction == 0 or direction == 2:
                step += 2
    
    direction = 2
    i = 2 * n - 1
    j = 2 * n 
    getAns(i, j, direction, answer)
    answer.pop()
    
    return answer

# Test Script
def reference(n):
    mat = lambda i, j : 4 * n * i + j + 1
    answer = []
            
    def getAns(i,j, direction, ans):
        ans.append(mat(i,j))
        step = 2
        while 0 <= i < 4*n and 0 <= j < 4*n:
            temp = 1
            while temp <= step:
                # 0->up, 1-> right, 2-> down, 3-> left
                if direction == 0:
                    i = i - 1
                elif direction == 1:
                    j = j + 1
                elif direction == 2:
                    i = i + 1
                else:
                    j = j - 1
                ans.append(mat(i,j))   
                temp += 1
            direction = (direction + 1)%4
            if direction == 0 or direction == 2:
                step += 2
    
    direction = 2
    i = 2 * n - 1
    j = 2 * n 
    getAns(i, j, direction, answer)
    answer.pop()
    
    return answer

def test():
    test_cases = [
        (1, reference(1)),
        (2, reference(2)),
        (3, reference(3)),
        (4, reference(4)),
        (5, reference(5)),
        (6, reference(6)),
        (7, reference(7)),
        (8, reference(8)),
        (9, reference(9)),
        (10, reference(10)),
    ]

    for n, expected_output in test_cases:
        try:
            output = solution(n)
        except Exception as e:
            error_message = (
                f"An exception occurred while running the test case:\n"
                f"`n`: {n}\n\n"
                f"Exception: '{str(e)}'"
            )
            assert False, error_message

        if output != expected_output:
            # Generate the 4n x 4n matrix for better debugging
            matrix = [[4 * n * i + j + 1 for j in range(4*n)] for i in range(4*n)]
            matrix_str = "\nMatrix (4n x 4n):\n" + "\n".join([str(row) for row in matrix])
            
            error_message = (
                f"The following Test Case failed:\n"
                f"`n`: {n}\n"
                f"{matrix_str}\n\n"
                f"Actual Output: {output}\n"
                f"Expected Output: {expected_output}"
            )
            assert False, error_message

test()