[Question]
  [
Given an input integer `n`, draw a number snake, that is, a grid measuring `n x n` consisting of the numbers `1` through `n^2` that are wound around each other in the following fashion:
Input `n = 3`:
```
7 8 9
6 1 2
5 4 3
```
Input `n = 4`:
```
 7  8  9 10
 6  1  2 11
 5  4  3 12
16 15 14 13
```
Input `n = 5`:
```
21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13
```
(Inspired by [this problem](https://projecteuler.net/problem=28) from Project Euler.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins!
  
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
1YL
```
[Try it online!](https://tio.run/##y00syfn/3zDS5/9/UwA "MATL – Try It Online")
### Explanation
Built-in... ¯\\_(ツ)\_/¯
[Answer]
# C#, ~~203~~ ~~202~~ ~~196~~ ~~193~~ 178 bytes
```
n=>{var r=new int[n,n];for(int o=n-2+n%2>>1,i=r[o,o]=1,c=2,w=o,h=o,b=1-2*(i%2),j;n>i++;){r[h,w+=b]=c++;for(j=0;j<i-1;++j)r[h+=b,w]=c++;for(j=0;j<i-1;++j)r[h,w-=b]=c++;}return r;}
```
*Saved a byte thanks to @StefanDelport.*  
*Saved 22 bytes thanks to @FelipeNardiBatista.*
This works by the following observation of how the squares are built up:
[![Image of square where n=5](https://i.stack.imgur.com/6Y5nn.png)](https://i.stack.imgur.com/6Y5nn.png)
As you can see each bit is added on to the previous square. For even numbers we go right of where we were, down till were one lower than where the square was and then left to the end. Odd numbers are essentially the opposite, we go left one, up till were one above the current height and then right to the end.
Full/Formatted version:
```
using System;
using System.Linq;
class P
{
    static void Main()
    {
        Func<int, int[,]> f = n =>
        {
            var r = new int[n, n];
            for (int o = n - 2 + n % 2 >> 1, i = r[o, o] = 1, c = 2, w = o, h = o, b = 1 - 2 * (i % 2), j; n > i++;)
            {
                r[h, w += b] = c++;
                for (j = 0; j < i - 1; ++j)
                    r[h += b, w] = c++;
                for (j = 0; j < i - 1; ++j)
                    r[h, w -= b] = c++;
            }
            return r;
        };
        Console.WriteLine(String.Join("\n", f(3).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
        Console.WriteLine(String.Join("\n", f(4).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
        Console.WriteLine(String.Join("\n", f(5).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
        Console.ReadLine();
    }
}
public static class ArrayExtensions
{
    public static T[][] ToJagged<T>(this T[,] value)
    {
        T[][] result = new T[value.GetLength(0)][];
        for (int i = 0; i < value.GetLength(0); ++i)
            result[i] = new T[value.GetLength(1)];
        for (int i = 0; i < value.GetLength(0); ++i)
            for (int j = 0; j < value.GetLength(1); ++j)
                result[i][j] = value[i, j];
        return result;
    }
}
```
[Answer]
# Dyalog APL, ~~70~~ ~~56~~ ~~45~~ 41 bytes
```
,⍨⍴∘(⍋+\)×⍨↑(⌈2÷⍨×⍨),(+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳
```
[Try it online!](http://tryapl.org/?a=%u236A%28%2C%u2368%u2374%u2218%28%u234B+%5C%29%D7%u2368%u2191%28%u23082%F7%u2368%D7%u2368%29%2C%28+%u2368%u23741%2C%u22A2%2C%AF1%2C-%29%28/%u2368%292/%u2373%29%A82+%u23734&run)
**How?**
```
(+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳
```
calculates the differences between the indices; `1` and `¯1` for right and left, `¯⍵` and `⍵` for up and down.
`1,⊢,¯1,-` comes as `1 ⍵ ¯1 ¯⍵`, `+⍨⍴` stretches this array to the length of `⍵×2`, so the final `2/⍳` can repeat each of them, with a repetition count increasing every second element:
```
      (1,⊢,¯1,-) 4
1 4 ¯1 ¯4
      (+⍨⍴1,⊢,¯1,-) 4
1 4 ¯1 ¯4 1 4 ¯1 ¯4
      (2/⍳) 4
1 1 2 2 3 3 4 4
      ((+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳) 4
1 4 ¯1 ¯1 ¯4 ¯4 1 1 1 4 4 4 ¯1 ¯1 ¯1 ¯1 ¯4 ¯4 ¯4 ¯4
```
then,
```
(⌈2÷⍨×⍨),
```
prepends the top-left element of the spiral,
```
×⍨↑
```
limit the first ⍵2 elements of this distances list,
```
+\
```
performs cumulative sum,
```
⍋
```
grades up the indices (`⍵[i] = ⍵[⍵[i]]`), to translate the original matrix with the indices of every element, and finally
```
,⍨⍴
```
shapes as a `⍵×⍵` matrix.
[Answer]
# C, ~~321~~ ~~307~~ ~~295~~ ~~284~~ ~~283~~ 282 bytes
*Thanks to both @Zachary T and @Jonathan Frech for golfing a byte!*
```
#define F for(b=a;b--;)l
i,j,k,a,b,m;**l;f(n){n*=n;l=calloc(a=m=3*n,4);F[b]=calloc(m,4);for(l[i=j=n][j]=a=k=1;n>k;++a){F[i][++j]=++k;F[++i][j]=++k;++a;F[i][--j]=++k;F[--i][j]=++k;}for(i=0;i<m;++i,k&&puts(""))for(j=k=0;j<m;)(a=l[i][j++])>0&&a<=n&&printf("%*d ",(int)log10(n)+1,k=a);}
```
Allocates a two-dimensional array of zeroes, then starts filling it from somewhere in the middle. Lastly the values that are larger than zero but smaller than or equal to the square of the input are printed.
[Try it online!](https://tio.run/##ZY/BbsMgDIbveYoo0yIIICVqd3LdY14iyoHQUpEAmdruFOXVl5lq3Q7lhL/vxzZGXYzZtrfT2bp4ztvczlc2oIZBKeA@c3KUk9RykAGqyoNlkS@xwggejfZ@NkxjwF0V5Z5D2w39E4cEUjffORwx9t3Yo8YJG4jHCYTQfGk713dCkBBiotdCuEcsVRSAh1fqzyv179fU22EN7hAo7ORUlp9f9xsrCs6TG2lWDSNZTjv61GoUoufHuiz1ASPFry7eLSveq1NeSEYF9/OlqemPopETag7rRjQP2kXGsyXL6Vi24/CcBL9o/4o@XlHT0HXdvo31@nLblA8/)
**Formatted:**
```
#define F for(b=a; b--;)l
i, j, k, a, b, m; **l;
f(n)
{
    n *= n;
    l = calloc(a=m=3*n, 4);
    F[b] = calloc(m, 4);
    for(l[i=j=n][j]=a=k=1; n>k; ++a)
    {
        F[i][++j] = ++k;
        F[++i][j] = ++k;
        ++a;
        F[i][--j] = ++k;
        F[--i][j] = ++k;
    }
    for(i=0; i<m; ++i, k&&puts(""))
        for(j=k=0; j<m;)
            (a=l[i][j++])>0 && a<=n && printf("%*d ", (int)log10(n)+1, k=a);
}
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~32~~ 29 bytes
```
1+×⍨-{⊖∘⌽⍣⍵⌽{⌽⍉,⌸⍵+≢⍵}⍣2⍣⍵⍪⍬}
```
[Try it online!](https://tio.run/##bZG9TsNAEIT7e4rpXCSWsns2wXkbK/iQhSWjhCay3EQI4ZBDUPBThwYhWiSERMWb7IuYDT/BQm7udufmmykuPS7Cg0ValIfhtEjn83zayuVNXsrZFbVuew4@7sQ/hpWsbuX8Xtbv4h/Ev@hQfS3NUNavKgyk2ehV6zP/WPyT@Oe6bU80p9oKzWamoxP/NglcmheBTqrP5OI0KI@C2pgMapDVcox9JCYbfm97IPBuixHBGguNvc66iDJIQKMOpyAYRB1YaVjQXx5pfAyKQNZE/1NZmxlswRE43jE8AnoKKQF6Skl9fcVjdLvj3279gdK5Tw "APL (Dyalog Classic) – Try It Online")
Uses `⎕io←1`. Starts with a 0-by-1 matrix (`⍪⍬`). 2N times (`⍣2⍣⍵`) adds the height of the matrix (`≢⍵`) to each of its elements, puts `1 2...height` on its right (`,⌸`), and rotates (`⌽⍉`). When that's finished, corrects the orientation of the result (`⊖∘⌽⍣⍵⌽`) and reverses the numbers by subtracting them from N2+1 (`1+×⍨-`).
[Answer]
# [PHP](https://php.net/), 192 bytes
```
for($l=strlen($q=($a=$argn)**2)+$d=1,$x=$y=$a/2^$w=0;$i++<$q;${yx[$w%2]}+=$d&1?:-1,$i%$d?:$d+=$w++&1)$e[$x-!($a&1)][$y]=sprintf("%$l".d,$i);for(;$k<$a;print join($o)."\n")ksort($o=&$e[+$k++]);
```
[Try it online!](https://tio.run/##HY7djoJAFIPv9yncSSGMxz@4dDjhQVhMSEYFITAOJECMz84evWz7tamr3JpmrnI/KP29YxUnyqy33kdoeRh9e@0iPDlCyV9Ab7eJJliOd5gZi7jH5IKJTwY1UYqnwWuZc0xBUryJYcM4O@@FrgPY7Awr3kQUxhrXHPP@V6ZFFDmWggfn6268RSpAqw5WStp8vhg0KUrzTTePvpZPvT6ov07pZuj9KJJD2SM0RIU26/oP "PHP – Try It Online")
Same way build a string instead of an array
[PHP](https://php.net/), 217 bytes
```
for($l=strlen($q=($a=$argn)**2)+$d=1,$x=$y=($a/2^$w=0)-!($a&1),$s=str_pad(_,$q*$l);$i++<$q;${yx[$w%2]}+=$d&1?:-1,$i%$d?:$d+=$w++&1)$s=substr_replace($s,sprintf("%$l".d,$i),($x*$a+$y)*$l,$l);echo chunk_split($s,$a*$l);
```
[Try it online!](https://tio.run/##HY7djoIwEIXvfYqVHExL6w9cig0PslFSKSxkGywtBojx2bH1cmbO950xrVkvhWnNBtL@9SJKsyhfm4cl0MKNVtc9wSAIpPgGaJJklEGJlGMWWMLlmN0wiRPdb/2wSymHC2hppCIlx5BA0xwdYxcMOV7L/Ispzq5vJqB2aXHee1cXQxVnKL@bGPOS4Hjeg8bWRsuqJnDcGdv1Y0OiGDo6KI9RTjAnkAwL9T08VNVV@/ip2mf/XzqjuzGQkN8v1vUD "PHP – Try It Online")
[Answer]
# PHP, ~~185 176~~ 174 bytes
```
for(;$n++<$argn**2;${xy[$m&1]}+=$m&2?-1:1,$k++<$p?:$p+=$m++%2+$k=0)$r[+$y][+$x]=$n;ksort($r);foreach($r as$o){ksort($o);foreach($o as$i)printf(" %".strlen($n).d,$i);echo"
";}
```
Run as pipe with `-nR` or [test it online](http://sandbox.onlinephpfunctions.com/code/01f51bef6102edba9a92eddd782f62ffe40650f2).
**breakdown**
```
for(;$n++<$argn**2;     # loop $n from 1 to N squared
    ${xy[$m&1]}+=$m&2?-1:1, # 2. move cursor
    $k++<$p?:               # 3. if $p+1 numbers have been printed in that direction:
        $p+=$m++%2+             # increment direction $m, every two directions increment $p
        $k=0                    # reset $k
)$r[+$y][+$x]=$n;           # 1. paint current number at current coordinates
ksort($r);              # sort grid by indexes
foreach($r as$o){       # and loop through it
    ksort($o);              # sort row by indexes
    foreach($o as$i)        # and loop through it
        printf(" %".strlen($n).d,$i);   # print formatted number
    echo"\n";               # print newline
}
```
[Answer]
# Mathematica, 177 bytes
```
(n=#;i=j=Floor[(n+1)/2];c=1;d=0;v={{1,0},{0,-1},{-1,0},{0,1}};a=Table[j+n(i-1),{i,n},{j,n}];Do[Do[Do[a[[j,i]]=c++;{i,j}+=v[[d+1]], {k,l}];d=Mod[d+1,4],{p,0,1}],{l,n-1}];Grid@a)&
```
[Answer]
# C++, ~~245~~ 228 bytes
```
void f(){for(int i=0,j=-1,v,x,y,a,b;i<n;i++,j=-1,cout<<endl)while(++j<n){x=(a=n%2)?j:n-j-1;y=a?i:n-i-1;v=(b=y<n-x)?n-1-2*(x<y?x:y):2*(x>y?x:y)-n;v=v*v+(b?n-y-(y>x?x:y*2-x):y+1-n+(x>y?x:2*y-x));cout<<setw(log10(n*n)+1)<<v<<' ';}}
```
[Try it online!](https://tio.run/##TZDdboMwDIXv/RSRprUJIROwX5EAz5ICbYPAoEIpUcWzs1Cmqb6wTj4fK7bzrhOnPF9eDOb1tSiJMm0/XErdpPDMGo2me0aNHs5v5xTg2hs8EdRN2Xc6L0k/FBLA4EBQLmNrCnKk7H5sL3RlJgn8KhGhP/qTb33tH6RRKA3nG87b66BUiUXNbmdTl5TzSiG7TwnVCb5GLKtiFJUIpU10Zpw2To8JPSRWoZhYhiIUkUcnZbMptixedbppgc45eiOnB2ezgtp0Wgte5Bpjy0OB/M8cedYxJrd5@nK40bo9hQFFDxkPmVKjUnuyl/O8rHs12iBlcAfi4jE5oblBkqYEyW7nUkoC9qhunjXcYeT/Y/2JKEXW3Tc6w7yEEME7fMAnfME3/EDwCw)
The function calculates and prints the value of each number of the matrix depending on its *x, y* position by applying this logic:
[![Snake values calculation depending on position](https://i.stack.imgur.com/WDPWe.jpg)](https://i.stack.imgur.com/WDPWe.jpg)
**Formatted version**:
```
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
void f(int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            int value = 0;
            // Invert x and y when n is even
            int x = n % 2 == 0 ? n - j - 1 : j;
            int y = n % 2 == 0 ? n - i - 1 : i;
            if (y < (n - x))
            {
                // Left-top part of the matrix
                int padding = x < y ? x : y;
                value = n - 1 - padding * 2;
                value *= value;
                value += y >= x ? n - x - y : n + x - y - (y * 2);
            }
            else
            {
                // Right-bottom part of the matrix
                int padding = x > y ? n - x : n - y;
                value = n - padding * 2;
                value *= value;
                value += x > y ? y - padding + 1 : n + y - x - (padding * 2) + 1;
            }
            cout << setw(log10(n * n) + 1);
            cout << value << ' ';
        }
        cout << endl;
    }
}
int main()
{
    int n;
    while (cin >> n && n > 0)
    {
        f(n);
        cout << endl;
    }
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~249~~ 247 bytes
I initialize an 2D array and find the starting point, which is the center for odd n or offset (-1,-1) for even n, then scale the fill/cursor pattern with the current 'ring' number. I feel like I'm missing a trick for interpreting the directions but I haven't come up with anything cheaper.
```
def f(n):
 M=[n*[0]for a in range(n)]
 x=y=n//2-1+n%2
 M[x][y]=i=s=1
 while 1:
  t=s*2
  for d in'R'+'D'*(t-1)+'L'*t+'U'*t+'R'*t:
   if i==n*n:print(*M,sep='\n');return
   v=[1,-1][d in'LU']
   if d in'UD':x+=v
   else:y+=v
   M[x][y]=i=i+1
  s+=1
```
[Try it online!](https://tio.run/##RU67boNAEOz5im2ivYeRc0RpSLZzaTeWqC5XIPsIJ1kLgrMDH56aHMhSmlnN7szs9HNsO35blqtvoBEsywxOZFnZV9d0A9QQGIaav326uQwmmon3@yIX/FJ8GpnUdnJ2dhRoJJPBTxtuHkyKgUijKtJcc64pB8@o8YBKxNxIjUdUUWO14TnhaoHQQCBixWU/BI5CnXaj7wm/GOXH4ON94FX2IGt2uXF2yz1W6J7mjVcHLCdNj3Xnb6Mv5yf57xp06gqjJrM0Yn0UuL9HIaVc3n@5yy/1pfV/ "Python 3 – Try It Online")
-2 thanks to Zachary T!
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~(...)~~ 83 bytes
Byte measured in UTF8, `\[LeftFloor]` (`⌊`) and `\[RightFloor]` (`⌋`) cost 3 bytes each. Mathematica doesn't have any special byte character set.
```
Table[Max[4x^2-Max[x+y,3x-y],4y
y-{x+y,3y-x}]+1,{y,b+1-#,b=⌊#/2⌋},{x,b+1-#,b}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxKSc12jexItqkIs5IF8So0K7UMa7QrYzVMankqtStBvMrdStqY7UNdaordZK0DXWVdZJsH/V0KesbPerprtWproCJ1saq/Q8oyswrcQjJDy4BMtId3IsyUxzSok1j/wMA "Wolfram Language (Mathematica) – Try It Online")
---
Uses the closed form for each of the 4 cases, then takes the maximum carefully to get the desired result.
Returns a 2D array of integers. I'm not sure if this is allowed, and although [it has been asked in the comments](https://codegolf.stackexchange.com/questions/125966/wind-me-a-number-snake/154458#comment309960_125966), the OP didn't reply.
[Answer]
## Clojure, 206 bytes
```
(defmacro F[s]`(if(~'r(+ ~'p ~'v ~s))~'v ~s))
#(loop[i 1 p(*(quot(dec %)2)(inc %))v 1 r{}](if(<(* % %)i)(partition %(map r(range i)))(recur(inc i)(+ p v)({1(F %)-1(F(- %))%(F -1)(- %)(F 1)}v)(assoc r p i))))
```
I guess this is a decent start, builds the board in sequence to a hash-map and then partitions it into `n x n` lists. That `defmacro` ended up being quite long, but the code is still shorter with it than without. Is there a more succint syntax to describe it?
Bulk of bytes calculate the starting point, and build the look-up logic of the next velocity `v`. Perhaps a nested `vec` would be better, but then you've got two indexes and velocities to keep track of.
[Answer]
# [J](http://jsoftware.com/), 41 bytes
```
(]|.@|:@[&0](|.@|:@,.*/@$+#\)@]^:[1:)2*<:
```
[Try it online!](https://tio.run/##y/r/P81WT0EjtkbPocbKIVrNIFYDwtTR09J3UNFWjtF0iI2zija00jTSsrH6n5qcka@QppCamJyhYKhgpGCsYKJg@h8A "J – Try It Online")
Does the same thing as [ngn’s APL submission](https://codegolf.stackexchange.com/a/154468/74681) but starts with a 1-by-1 matrix and repeats 2×N−2 times.
[Answer]
# Python 165 (or 144)
```
from pylab import *
def S(n):
 a=r_[[[1]]];r=rot90;i=2
 while any(array(a.shape)<n):
  q=a.shape[0];a=vstack([range(i,i+q),r(a)]);i+=q
 if n%2==0:a=r(r(a))
 print(a)
```
This creates a numpy array, then rotates it and adds a side until the correct size is reached. The question didn't specify if the same start point needs to be used for even and odd numbers, if that's not the case the line `if n%2==0:a=r(r(a))` can be removed, saving 21 bytes.
[Answer]
# [J](http://jsoftware.com/), 41 bytes
```
,~$[:/:[:+/\_1|.1&,(]##@]$[,-@[)2}:@#1+i.
```
## standard formatting
```
,~ $ [: /: [: +/\ _1 |. 1&, (] # #@] $ [ , -@[) 2 }:@# 1 + i.
```
This approach is based off [*At Play With J Volutes*](https://www.jsoftware.com/papers/play132.htm) (Uriel's APL uses a similar technique).
It's unexpected and elegant enough to justify a 2nd J answer, I thought.
Essentially, we don't do anything procedural or even geometric. Instead, we arithmetically create a simple sequence that, when scan summed and graded up, gives the correct order of the spiraled number from left to right, top to bottom. We then shape that into a matrix and are done.
I'll add a more detailed explanation when time permits, but the linked article explains it in depth.
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/depUoq30raKttPVj4g1r9AzVdDRilZUdYlWidXQdojWNaq0clA21M/X@a3KlJmfkK6QpmEAY6uowAdP/AA "J – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 38 bytes
```
{(x,x)#<0,+\(,/-:\1,x)4!-1_&1+-1_&x#2}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700Oz4vPW_BgqWlJWm6Fjc10qyqNSp0KjSVbQx0tGM0dPR1rWIMgXwTRV3DeDVDbRBZoWxUC1WvW5xhlWBgpaGjpKSpo6SgpK-uol9jqKFbo6-vbKWurhmjYsVVnKGepm6irWhqDdEEswwA)
[Answer]
# [Python 3 (Stackless)](https://github.com/stackless-dev/stackless), ~~192~~ ~~188~~ ~~179~~ 150 bytes
```
lambda n:[list(map(v,list(range(t-n,t)),[y]*n))for t in[1+n//2]for y in range(n-t,-t,-1)]
v=lambda x,y,r=0:y>=abs(x)and(3-2*r+4*y)*y+x+1or v(y,-x,r+1)
```
[Try it online!](https://tio.run/##RY7LCoMwFET3fkWWuXlgo6ULIf0R6yJWbaV6lSRI8vWptoXCLObAcJg1@ueCpXTe3F9T71wa9C1NZm47Q7Cqp9F5OpuVbuJTrcFHT71E4QFEHRuGAMNiiScj1opjnhfNwXFn8l2j9OKIgibb9M8dRBRWn6p41aZ1NIDBjpayYJafWQQWeeBq92w0ChmE5QrS4cW/9wJVRlY7oqcD3W@kNw "Python 3 (Stackless) – Try It Online")
The algorithm here is to form a phasor for each coordinate in the grid, and then rotate it 90-degrees clockwise until the phasor lies between the upper diagonals. A simple formula can be used to calculate the value based on the coordinates and the number of clockwise rotations:
$$
(2y+1)^2-(y-x)-2yr
$$
Saved 4-bytes since 90-degree phasor rotation is easily done without complex numbers
[Answer]
# [R](https://www.r-project.org/), 183 bytes
```
x=scan()
b=t(d<-1)
while(2*x-1-d){m=max(b)
y=(m+1):(m+sum(1:dim(b)[2]|1))
z=d%%4
if(z==1)b=cbind(b,y)
if(z==2)b=rbind(b,rev(y))
if(z==3)b=cbind(rev(y),b)
if(z==0)b=rbind(y,b)
d=d+1}
b
```
[Try it online!](https://tio.run/##PY5BbsIwEEX3PoWlCmmmkKgOsEHMSSoWdmy3lrBBTigOIWdPY0GyeYv3/x9NHD/4Pcorb2oZALkLXHJ7C3XrLoHbS@RGNs5E3pqmdeGHWZpTSNjn1bFYTFmW2KdhTPQ6xxS1oI@FQHb/dWcD1WcqRKGx9@RlAoWsI/BrgYeJzc2DOGjnJ/9dnZ4CkT1Ir1Y75iw8iAQqqpULGtSmw7esJhnfMpo/6HBOtkv95TdqTr6WTZelJr0WA1PjwCxMv1qoMrYZu4w9jv8 "R – Try It Online")
Output is a matrix snake (or snake matrix, whatever). It's probably not the most efficient method, and it could likely be golfed, but I thought it was worth showing. I'm rather proud of this actually!
The method builds the matrix from the inside out, always appending an additional number of integers equal to the number of columns in the matrix before appending.
The pattern that follows is either binding by columns or by rows, while also reversing some values so they are appended in the correct order.
# 193 bytes
Exact same as above, but final `b` is
```
matrix(b,x)
```
[Try it online!](https://tio.run/##PY5BbsMgEEX3nAKpijTT2FZx0k0UThJ1AQZapEAqTBIc12d3QYm9eYv3549@mN/oPYhf2nfCA1LrqaDm6rtoL56aS6Ba9FYHGnUfrf8mhi8pJBxL61ivpmkaHNM0J/58RySPoI41Q3L/sWcN7XuqWa1wdNyJBBLJwMFtGR4y@6sDdlDWZX9qv/4YInlwtdnsiTXw4Jyh5J20XoGsBnzJNsvwkkHfYMAl2a3nT1/JJflYO0ORiqstm4gTMdg8qko4T8RAXm2gLdgV7As@cf4H "R – Try It Online")
which gives slightly cleaner output, but I didn't see any special criteria for output, so the first answer should work if I'm not mistaken.
]