0

Cubically, 46 bytes
$:7*7(R1B1L1F1-7)6~(~F3L3B3R3?0@7)0(~>7?6&!@7)
Will not work on TIO (as of now) because of some strange behavior with reading input directly after a loop ()6~ loads the input -1, but )6\n~ loads the input 32). This must be run on the Lua interpreter with experimental mode e...