Spiral Matrix

Traverse a 2D matrix in spiral order starting from the top-left corner.

Code

Algorithms
echo "$matrix" | jq 'def spiral: if length == 0 then [] else .[0] + ([.[1:][] | .[-1]] | if . == [[]] then [] else . end) + (if length > 1 then ([-1]|reverse) else [] end) + ([.[1:-1][] | .[0]] | reverse) + (.[1:-1] | map(.[1:-1]) | spiral) end; spiral'

Parameters

2D matrix (JSON)

Server

More Bash Snippets