Skip to content

Instantly share code, notes, and snippets.

@DataKinds
Created July 30, 2024 06:36
Show Gist options
  • Save DataKinds/0fc739bb868fdc44db571e321d8b9ab0 to your computer and use it in GitHub Desktop.
Save DataKinds/0fc739bb868fdc44db571e321d8b9ab0 to your computer and use it in GitHub Desktop.
NB. https://leetcode.com/problems/spiral-matrix/
]in=: 1+3 3$i.9
]in2 =: 1+3 4$i.12
walk=: 3 : 0 NB. call with `walk in`
i=. 0 0
d=. 0 NB. R D L U
m=. ($ y) $ 0
o=. a:
tl_bound=. [: +/ 0&>
br_bound=. [: +/ ($y)&<:
bounded=. tl_bound + br_bound
while. (~. , m) -.@-: 1 do.
o=. o,<i
m=. 1 (<i)} m
ni=. i+(d { 0 1,1 0,0 _1,:_1 0) NB. Peek forward
if. ((m {~ <ni |~ $y) + (bounded ni)) -: 0 do.
i=. ni
else.
d=. 4 | d+1
ni=. i+(d { 0 1,1 0,0 _1,:_1 0) NB. Peek right
if. ((m {~ <ni |~ $y) + (bounded ni)) -: 0 do.
i=. ni
else.
break.
end.
end.
end.
(}. o) { y
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment