[Question]
  [
This challenge is inspired by [this](https://codegolf.stackexchange.com/q/156856/31516), now deleted question.
---
Take a positive integer **N** as input, and output a matrix with the numbers **1 .. N2** that follows the pattern below:
Fill in the first row with **1 .. N** then fill the last row (row number **N**) with **(N+1) .. 2N**, then fill the second row with **(2N+1) .. 3N** and continue until you have filled all rows.
The output format is flexible, so list of lists etc. are accepted.
```
N = 1
1
N = 2
1  2
3  4
N = 3
1  2  3
7  8  9
4  5  6
N = 4
 1  2  3  4
 9 10 11 12
13 14 15 16
 5  6  7  8
N = 5
 1  2  3  4  5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
 6  7  8  9 10
```
Standard rules apply. Shortest answer in bytes in each language wins. Explanations are encouraged as always.
  
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 8 bytes
Saved 5 bytes thanks to *Rod*
```
nLôÂ«āÉÏ
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/z@fwlsNNh1YfaTzcebj//38zAA "05AB1E – Try It Online")
**Explanation**
```
n           # push input^2
 L          # push range [1 ... input^2]
  ô         # split into pieces each the size of the input
   Â«       # append the reverse of this 2D-list
     ā      # push range [1 ... len(list)]
      É     # check each element for oddness
       Ï    # keep only the elements in the 2D list which are true in this list
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
->n{r=*1..n*n;n.times{|x|p r.slice!(r[x*=n]?x:-n,n)}}
```
## Explanation:
Put all the numbers into a single array first, then slice the array skipping a line for each iteration. After the first (n/2+n%2) iterations there is nothing left to skip, then get all the remaining lines backwards.
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vushWy1BPL08rzzpPryQzN7W4uqaipkChSK84JzM5VVGjKLpCyzYv1r7CSjdPJ0@ztva/BlC9qaZebmIBSGladEWsdUFpSbGCuq6urnrtfwA "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
```
def f(n):a=range(n);print[[i*n-~j for j in a]for i in a[::2]+a[~(n%2)::-2]]
```
[Try it online!](https://tio.run/##JcyxCoAgFEDRX3lLoJWQji/6EnEQ0tLhGdJQi79uWduBC/e4zz2RqnV1HjwjjnbJljb3cj5yoFPr0JMoEXzKECEQWNMYPmpEZQarC6NOcUShjKktXy3/JznKiaNnF68P "Python 2 – Try It Online")
[Answer]
# JavaScript, 68 bytes
*Edit* 3 bytes saved, whetted by @user71546
~~First try,~~ following the obvious route: count from 1 and fill the array from both sides, from outer to inner
```
n=>(v=0,q=[...Array(n)]).map((_,i)=>q[i&1?--n:i/2]=q.map(_=>++v))&&q
```
**Test**
```
var F=
n=>(v=0,q=[...Array(n)]).map((_,i)=>q[i&1?--n:i/2]=q.map(_=>++v))&&q
function test() {
  var n=+N.value;
  O.innerHTML = '<tr><td>'
  +F(n).map(r=>r.join('</td><td>')).join('</td></tr><tr><td>')
  +'</td></tr>'
}
test()
```
```
#O { margin: 1em }
td { text-align: right }
```
```
<input id=N type=number min=1 value=5 oninput='test()'>
<table id=O>
```
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
(0#)
m#n|m>=n^2=[]|k<-m+n=[m+1..k]:(k+n)#n++[[k+1..k+n]|k<n^2]
```
[Try it online!](https://tio.run/##TY1LT4NAFIX391eclA1kAuEOjxbjsHGrpokbE4oJMaLNMBPS4sr618VhsImb@zjnfud@dGf9NgxzD3WYwzSIyAT2YmplX6Rq2ou@jY2wqjGCk0S3N6EWNgqsEE2jvSTscuSu29l0RwsF040PCMO6Hj@np@l0bzebCMkqj6ejndzSR2gcXbREXzE9OoqJyQ@SGK5kQL4KmRfg@hbYARXlQAGUq50T/vyFQAVOwQx2ORk4BxfgkjwALAkrVvzHXB55BleGJENKyAwyh3RuCd6Cd@AKMqVrFvw/ir/nn9d@6N7Pc/x8t9//Ag "Haskell – Try It Online") Output is a list of lists, e.g. `(0#) 3` yields `[[1,2,3],[7,8,9],[4,5,6]]`.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~51+3=54~~ 47 bytes
```
:&v
?!\1-:&:&*}}r:
 ~\
!~>1+::n&:&%:a84*@@?$~o?
```
[Try it online!](https://tio.run/##S8sszvj/30qtjMteMcZQ10rNSk2rtrbIikuhLoZLsc7OUNvKKg8oqGqVaGGi5eBgr1KXb////3/dMgVTAA "><> – Try It Online")
Input is expected on top of the stack at program start using the `-v` flag. Output consists of non-aligned numbers separated by single spaces, and each line is separated by a single newline. Example output for `N=5`:
```
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
6 7 8 9 10
```
... followed by a single newline. Program terminates with an error (`something smells fishy...`), but that's on STDERR rather thatn STDOUT.
**Explaination:**
The first line simply stores a copy of `N` in the register.
The second line builds up the offset for each output row by subtracting 1 from `N`, multiplying this by `N`, rotating it to the bottom of the stack and then reversing the entire stack. When the number on top of the stack reaches 0, the stack should look like this (example uses `N=5`):
```
5 15 20 10 0 0
```
The third line discards the duplicate `0` from the top of the stack.
The fourth line increments the top of the stack and outputs a copy of it. This is then taken mod `N`, and this is used to decide if a space or newline should be printed, and if the top of the stack should be discarded - if last number printed is `x`, then `x mod N == 0` indicates that the end of that output row has been reached. Execution ends when `1+` gets executed on an empty stack, throwing the termination error.
**Previous version**
This explicitly checked for an empty stack to end execution, and I was also including 3 bytes for the `-v` flag usage.
```
:&v
?!\1-:&:&*}}r:
 ~\
!;>1+::n&:&%:a84*@@?$~o?!~l?
```
[Try it online!](https://tio.run/##S8sszvj/30qtjMteMcZQ10rNSk2rtrbIikuhLoZL0drOUNvKKg8oqGqVaGGi5eBgr1KXb69Yl2P///9/3TIFYwA "><> – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), `-p` ~~52~~ 51 bytes
```
#!/usr/bin/perl -p
map{$|--?$\="@0
".$\:say"@0";$_+=@0for@0}@0=1..$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2igZ2D9PzexoFqlRlfXXiXGVsnBgEtJTyXGqjixEshWslaJ17Z1MEjLL3IwqHUwsDXU01OJr63@/9/0X35BSWZ@XvF/3QIA "Perl 5 – Try It Online")
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 101 bytes
```
n->{int x[][]=new int[n][n],i=0,j;for(;i<n;i++)for(j=0;j<n;)x[i%2<1?i/2:n+~i/2][j]=++j+i*n;return x;}
```
[Try it online!](https://tio.run/##dY8xT8MwEIX3/IpbkJKmDW0lBuq4iAWJgaljlMG0SXUmPUeOU1pV4a@HMzUwICRL53v33vmzVkc1M21Fevd2P@KhNdaBZjHrHTbZRER/tLqnrUNDftj2rw1uYduoroMXhQSXCKBzyrHKN4Bnck8hkCO5oizKNdQgR5qtLyzAyUuSqnfwYyr5TFHOp1rUxsYCcxKYpolvtJwLzX1yKvBmmS8e8Ha5ovSDS1noUqapTnFCwlautwQnMYyCIQJkoDoa3MGBUeONs0j7ogRl913yRQ7A70DsuQgkLASXXMIdV2YIFoDwEQ5adWZfnam2bc4xJSI4vtd40@rq@40DbM6dqw6Z6V3WMoRrKH70ni5z5ooVq@Rn2RD9mwoe7xiiYfwE "Java (OpenJDK 9) – Try It Online")
### Credits
* -4 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
[Answer]
## JavaScript (ES6), ~~69~~ 68 bytes
```
n=>[...Array(n)].map((_,i,a,j=((i*=2)<n?i:n+n+~i)*n)=>a.map(_=>++j))
```
~~Well it got outgolfed before I could post it but here it is anyway.~~ Edit: Saved 1 byte thanks to @KevinCruijssen.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
²ss2Ṛj@/Fs
```
[Try it online!](https://tio.run/##y0rNyan8///QpuJio4c7Z2U56LsV/zc0UDjc/qhpjYI7iMh61Ljv0LZD2/4DAA "Jelly – Try It Online")
### How it works
```
²ss2Ṛj@/Fs  Main link. Argument: n
²           Square; yield n².
 s          Split; promote n² to [1, ..., n²] and split it into chuks of length n.
  s2        Split 2; generate all non-overlapping pairs of chunks.
            If n is odd, this leaves a singleton array at the end.
    Ṛ       Reverse the order.
     j@/    Reduce by join with reversed arguments.
            In each step, this places the first and second element of the next pair
            at the top and bottom of the accumulator.
        Fs  Flatten and split to restore the matrix shape.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
│æ╘▐⌡r▌═∟Y
```
[Run and debug it online](https://staxlang.xyz/#c=%E2%94%82%C3%A6%E2%95%98%E2%96%90%E2%8C%A1r%E2%96%8C%E2%95%90%E2%88%9FY&i=1%0A4%0A5%0A12&a=1&m=2)
The corresponding ascii representation of the same program is 12 characters.
```
JRx/r{]+rFmJ
```
Here's how it works.
```
JR              range [1 .. x^2] where x=input
  x/            split into subarrays of size x
    r           reverse
     {   F      for each subarray, execute block
      ]+r       concat array, and reverse result
          m     for each row, output ...
           J        each subarray joined by spaces
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~...~~ 6 bytes
Thanks [*JonathanAllan*](https://codegolf.stackexchange.com/users/53748) for -1 byte!
```
²sm0m2
```
[Try it online!](https://tio.run/##y0rNyan8///QpuJcg1yj////mwIA "Jelly – Try It Online")
---
Use an identical algorithm to the 05AB1E answer.
[Answer]
# [R](https://www.r-project.org/), ~~70~~ ~~59~~ 47 bytes
```
function(n)matrix(1:n^2,n,,T)[c(1:n,n:1)*!0:1,]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPMzexpCizQsPQKi/OSCdPRydEMzoZxNPJszLU1FI0sDLUif2fpmGoyZWmYQQijEGECYgw1fwPAA "R – Try It Online")
Thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for a 4 byte golf, which I then golfed further.
Returns a matrix; constructs the `matrix` in sequence, e.g., `[[1 2 3] [4 5 6] [7 8 9]]`, then rearranges the rows.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~72~~ ~~68~~ 63 bytes
-4 bytes thanks to Neil
```
def f(n):w=zip(*[iter(range(1,n*n+1))]*n);print(w+w[::-1])[::2]
```
[Try it online!](https://tio.run/##NcsxDoAgDADAr3RsQQcYHDC@hDCYCMpSCCEB/Ty6ON10@a5XYj3G4QMEZDJte2JGYWP1BcvOp0c1sWCpiJxgWnOJXLHJZo2ZlaMP7UZIBTpEhr8sZAJ2Gi8 "Python 2 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 102 bytes
```
n=input('');A=B=vec2mat(1:n*n,n);i=j=0;do
B(++i,:)=A(++j,:);if++j<n
B(n-i+1,:)=A(j,:);end;until j>=n
B
```
[Try it online!](https://tio.run/##JcoxCoQwEEbhfk9hZ2IUdGEbxxH0JqIRJri/FtHrx0G7B9/b5zhdPiWw4DijyXNLA498@fn7n6JpWhQoYUk4cE3L/hmNc1K2lgeNoEGyanRQQSWuee0Rj4VORNmy0LMOKf1u)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 110 bytes
```
i,c,t,b;f(a,n)int*a;{for(b=n-1;i<n*n;t++,b--){for(c=0;c<n;)a[t*n+c++]=++i;for(c=0;c<n&i<n*n;)a[b*n+c++]=++i;}}
```
[Try it online!](https://tio.run/##bdLNioMwEAfwu09RhC6JidD4CZuGfRDrIaZYctjpUsJeis/uRrOW7DrixZnkNyP8TX4zZp4tN9zxQY5Ec6AWXKblc7w/yKAgF9KeIQPpGONDntO1YdRJmjNIqjuXATOM9YoxK6PeW7jmTwzxiWma/YDDp7ZAaPJMDv5ZCqCEfH1o0UHv31AZCVl2olr47ULp6@Erf8vhsnJ@OqgisorO7/GfKnCq2FNlRJUYVeJUuaeqiKowqsKpak/VEVVjVI1T9Z5qIqrBqAanmj3VRlSLUS1OhfKUJN93e/1trTHkIRtbUJZ4WT/JR0taxuha3BpbJk3ceI0aSXq8Hk3KdWeXPPbc5MDER1m8i9P2H9vJC1wgXTaafwA "C (gcc) – Try It Online")
Fills out an array by alternating between 2 indices for rows: one index starting at the top and one starting at the bottom. The top row index starts at 0 and is incremented every 2 rows; the bottom row index starts at n-1 and is decremented every 2 rows.
Ungolfed:
```
void f(int* a, int n)
{
    //i = value to be written [1,n]; c = column index; t = top row index; b = bottom row index
    for(int i=1, c=0, t=0, b=n-1;
        i <= n*n; //when i = n*n, we have written all the values and we're done
        t++, b--) //t increments every 2 rows, b decrements every 2 rows
    {
        //write out 2 rows per loop
        //first row: fill out row at t
        for(c=0; c<n; c++, i++)
            a[t*n+c]=i;
        //second row: fill out row at b
        //this step will be skipped on the final loop for odd values of n, hence the (i<=n*n) test
        for(c=0; c<n && i<=n*n; c++, i++) 
            a[b*n+c]=i;
    }
}
```
[Answer]
# C++ + [Range V3](https://github.com/ericniebler/range-v3/tree/1a9701d619d9d073151ccf86e37a8e6afb1a732c), 159 bytes
```
#include<range/v3/all.hpp>
using namespace ranges::view;
[](int n){auto r=iota(1,n*n+1)|chunk(n);return concat(r|stride(2),r|reverse|drop(n%2)|stride(2));}
```
[Live on Wandbox](https://wandbox.org/permlink/aw2GhEbmt2PN3Sey)
Not counting the 2 newlines after `using namespace range::view`; they are just there to separate imports from the lambda.
Mildly interesting fact: this solution makes no heap allocations. It solves the problem in `O(1)` space.
---
Explanation:
1. `iota(1, n*n+1)` -> `[1 ... n*n]`
2. `chunk(n)`: every `n` elements together, so `[1 ... n] [n+1 ... 2*n] ...`
3. Call that `r`
4. `r | stride(2)`: take every other element: `[1 ... n] [2*n+1...] ...`
5. concatenate that with:
6. `r | reverse | drop(n % 2)`: reverse, then drop the `[1 ... n]` term if `n` is odd (there'll be an odd number of rows and we only want to print the first term once). It seems like I should be able to just do `r | reverse | take`, but that doesn't work for some reason.
7. `stride(2)` again, take every other element. This time it's in reverse.
More readable, and testable:
```
#include <range/v3/all.hpp>
using namespace ranges::view;
auto f(int n)
{
    auto rows = iota(1, n * n + 1)
        | chunk(n);
    return concat(
        rows | stride(2),
        rows
            | reverse
            | drop(n % 2)
            | stride(2));
}
#include <iostream>
int main(int argc, char** argv)
{
    std::cout << "N = " << argc << '\n';
    auto res = f(argc);
    for (auto const& row : res | bounded) {
        for (auto const& elem : row | bounded) {
            std::cout << elem << ' ';
        }
        std::cout << '\n';
    }
}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 19 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Anonymous tacit prefix function.
```
(⍋1∘+|-\⍤⍳)⊇,⍨⍴∘⍳×⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NRb7fho44Z2jW6MY96lzzq3az5qKtd51Hvike9W4DiQIHD04G8/2mP2iY86u171NX8qHcNUO7QeuNHbRMf9U0NDnIGkiEensH/0xQMuXR1dbnSFIygtDGUNoHSpgA "APL (Dyalog Extended) – Try It Online")
`×⍨` self-multiplicate (i.e. square **N**)
`∘⍳` **ɩ**ndices one through that, then:
 …`⍴` **r**eshape to the following shape:
  `,⍨` self-concatenate (i.e. \$N\$-by-\$N\$ matrix)
`(`…`)⊇` permute the rows into the following order:
 `∘⍳` **ɩ**ndices one through \$N\$, then
  `-\` alternating sum; \$\big\{1,(1-2),(1-2+3),(1-2+3-4),…,(1-2+3-…\pm N)\big\}=\Big\{1,-1,2,-2,…,\pm\big\lfloor\frac{N}2\big\rfloor\Big\}\$
 …`|` division remainder when divided by:
  `1∘+` the incremented \$N\$
 `⍋` grade (permutation that would sort)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
s2ZU2¦Ẏị²s$
```
[Try it online!](https://tio.run/##y0rNyan8/7/YKCrU6NCyh7v6Hu7uPrSpWOX///@mAA "Jelly – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 22 bytes
```
ri__*,:)/2/z[1W].{%:p}
```
[Try it online!](https://tio.run/##S85KzP3/vygzPl5Lx0pT30i/KtowPFavWtWqoPb/fxMA "CJam – Try It Online")
[Answer]
# C (gcc) ~~80~~ ~~78~~
I see now this solution is wrong
```
i;f(n){for(i=0;i++<n*n;printf("\n%3d"+!!(~-i%n),i>n?n+(i+n>n*n?i%n?:n:i):i));}
```
[Try it online!](https://tio.run/##HcqxCsJAEITh3rdIILDrGoiJNlnNvYhNOLmwhaMEuxBf/VwOhq8Y/tguMeZsmgi8pfdKdu/URG44Qj@r4ZuofqAZnrVUFf1aa8AnmxAgZILJu@BfGDEa@1j3/JoNxNsh0ZnV7YtD8VK8unv@Aw)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 36+8+61 = 105 bytes
compile with `-Dp=printf("%d ",i),i++%n;);puts("")` `-Dq=i,n)`
```
f(q{g(1,i);}g(q{for(;p;i<n*n&&h(q;}h(q{for(n+i<n*n&&g(n+q;p;}
```
[Try it online!](https://tio.run/##RY3BCsIwDIbve4pR2EjddtCbxN58DC@j0i6gsd3mafTVrSlMvISfL/@X2MFbm7ODuHk49qQxecnuNQMGpAsfuG0niJimHXO3Uy8xSinl50gMeqvKmnityZxEPSN1ndAwC3OgmvuNVflQOSgzvNcFlJKUqpQ/1j1Gv@ThGszfqIvQy52GUePPkFI01LP@Ag "C (gcc) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs a 3D array; add `c1` at the end for `+2` bytes to flatten by one level.
```
²õ òU ó oÔ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=svUg8lUg8yBv1A&input=NQotUQ)
]