## Snail Sort

Given an `n x n` array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

```
array = [[1,2,3],
         [4,5,6],
         [7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
```

For better understanding, please follow the numbers of the next array consecutively:

```
array = [[1,2,3],
         [8,9,4],
         [7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
```

This image will illustrate things more clearly:



NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.

NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array `[[]]`.

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = 'def snail(array):\n    mission = Game(array)\n    path = []\n    while mission.we_are_not_done:\n        path.append(mission.dig_at_location())\n        if mission.it_is_safe_to_slither:\n            mission.slither_onwards_good_soldier()\n        else:\n            mission.turn_away_from_fire()\n            mission.slither_onwards_good_soldier()\n    return path\n\n\nclass Game(object):\n    def __init__(self, array):\n        self.map = array\n        self.moves_left = len(array) * len(array[0])\n        self.coords = {"x": 0, "y": len(array)-1}  # start in NW area.\n        self.dir = "E"  # slitherin\' east.\n        self.fire = {"min_x": -1, "min_y": -1, "max_x": len(array),\n                     "max_y": len(array)}  # the carpet is lava.\n        self.rules = {"N": {"x": 0, "y": 1, "turn": "E"},\n                      "E": {"x": 1, "y": 0, "turn": "S"},\n                      "S": {"x": 0, "y": -1, "turn": "W"},\n                      "W": {"x": -1, "y": 0, "turn": "N"}}\n\n    def slither_onwards_good_soldier(self):\n        self.coords["x"] = self.next_x\n        self.coords["y"] = self.next_y\n        self._subtract_move()\n\n    def turn_away_from_fire(self):\n        self._become_aware_that_the_world_is_closing_in()\n        self.dir = self.rules[self.dir]["turn"]\n\n    def dig_at_location(self):\n        # have to invert the y location for the purpose of the array.\n        return self.map[len(self.map)-self.coords["y"]-1][self.coords["x"]]\n\n    def report_in(self):\n        print(("Dear Sir! I\'m stationed @ x: %s, y: %s, heading %s." %\n              (self.coords["x"], self.coords["y"], self.dir)))\n\n    @property\n    def it_is_safe_to_slither(self):\n        x = self.next_x\n        y = self.next_y\n        if x != self.fire["min_x"] and \\\n           x != self.fire["max_x"] and \\\n           y != self.fire["min_y"] and \\\n           y != self.fire["max_y"]:\n            return True\n\n    @property\n    def we_are_not_done(self):\n        if self.moves_left > 0:\n            return True\n\n    @property\n    def next_x(self):\n        return self.coords["x"] + self.rules[self.dir]["x"]\n\n    @property\n    def next_y(self):\n        return self.coords["y"] + self.rules[self.dir]["y"]\n\n    def _become_aware_that_the_world_is_closing_in(self):\n        if self.dir == "N":\n            self.fire["min_x"] += 1\n        if self.dir == "E":\n            self.fire["max_y"] -= 1\n        if self.dir == "S":\n            self.fire["max_x"] -= 1\n        if self.dir == "W":\n            self.fire["min_y"] += 1\n\n    def _subtract_move(self):\n        self.moves_left -= 1\n'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'snail'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: 7220