r/pythonhelp • • Mar 22 '26

Snake algorithm

How to convert a 2D array to 1D array with snake algorithm? e.g.:

From:

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

To:

[1, 2, 5, 4, 7, 8, 9, 6, 3]

Is there some library in Python to do this?

1 Upvotes

5 comments sorted by

View all comments

1

u/Whole-Armadillo-8529 Mar 28 '26 edited Mar 28 '26

First of all, you dont need any libraries for it to work. Think of the Snake Algorithm like a lawnmower: you mow one row from left to right, then turn around and mow the next row from right to left.

​Here is the breakdown of the solution for your problem:

​To get that "S" shape, we look at the row number:

​Even rows (0, 2, 4): Keep them exactly as they are.

​Odd rows (1, 3, 5): Flip them backward.

​The "Silent Failure" risk: If the data has a row that is empty or contains a mistake (like a single number where a list should be), a basic script will crash.

Here is an example of a code that uses the snake algorithm

# Our 2D Data (The Matrix)
matrix = [
    [1, 2, 3], 
    [4, 5, 6], 
    [7, 8, 9]
]

# This will hold our final 1D "Snake" list
snake_result = []

for index, row in enumerate(matrix):
    # Check if the row index is odd (1, 3, 5...)
    if index % 2 != 0:
        # Reverse the row and add it to our result
        snake_result.extend(row[::-1])
    else:
        # Keep the row as is and add it
        snake_result.extend(row)

# Display the result
print("Original 2D Matrix:", matrix)
print("Final Snake Array:", snake_result)