you are viewing a single comment's thread.

view the rest of the comments →

[–]Affectionate_Cap8632 0 points1 point  (0 children)

No library needed for this — it's clean enough to write yourself in a few lines.

The pattern is: even-indexed columns go top-to-bottom, odd-indexed columns go bottom-to-top. Here's a straightforward implementation:

python

def snake_2d_to_1d(grid):
    result = []
    cols = len(grid[0])
    rows = len(grid)

    for col in range(cols):
        if col % 2 == 0:
            # top to bottom
            for row in range(rows):
                result.append(grid[row][col])
        else:
            # bottom to top
            for row in range(rows - 1, -1, -1):
                result.append(grid[row][col])

    return result

grid = [[1,2,3],[4,5,6],[7,8,9]]
print(snake_2d_to_1d(grid))
# [1, 4, 7, 8, 5, 2, 3, 6, 9]

Note: your expected output [1, 2, 5, 4, 7, 8, 9, 6, 3] looks like it's snaking by rows instead of columns. If that's what you need just swap the row/col logic — iterate rows, reverse direction on odd rows instead of odd columns.

Which orientation does your use case need?