New: 213 pattern programs with tested code in C, C++, Java and Python Explore patterns

Reverse Spiral Matrix (Spiral From the Centre)

The reverse spiral matrix puts 1 in the centre and spirals outwards, so the largest number, 25, ends up in the corner. Some sites call it the anti-spiral; it is the spiral matrix read backwards.

Quick answer: Fill an ordinary clockwise spiral from the top-left corner, then print n² + 1 − a[i][j] instead of a[i][j]. The first cell of the walk gets n² and the last one, in the centre for an odd n, gets 1.

This program is part of the Spiral Patterns collection.

Table of contents8 sections
  1. Reverse Spiral Matrix output
  2. How the reverse spiral matrix works
  3. Reverse Spiral Matrix in C
  4. Reverse Spiral Matrix in C++
  5. Reverse Spiral Matrix in Java
  6. Reverse Spiral Matrix in Python
  7. Time and space complexity
  8. Frequently asked questions

Reverse Spiral Matrix output

Output (n = 5):

 25 24 23 22 21
 10  9  8  7 20
 11  2  1  6 19
 12  3  4  5 18
 13 14 15 16 17
Reverse Spiral Matrix layout diagram, row by row (n = 5)
The numbers of the reverse spiral matrix laid out row by row (n = 5).

How the reverse spiral matrix works

Walking a spiral from the centre outwards is fiddly, because the runs get longer as you go. Walking inwards from a corner is easy: turn whenever you hit the edge or a filled cell. So the program walks inwards and reverses the numbers when it prints them. Subtracting from n² + 1 turns 1 into 25 and 25 into 1, which flips the direction of travel without changing the path.

  1. Fill an n × n grid with zeros and start in the top-left cell.
  2. For each value from 1 to the last one: write it in the current cell.
  3. Try to step in the current direction. If that cell is outside the grid or already filled, turn to the next direction and try again.
  4. Print n² + 1 − a[i][j] for every cell, row by row.

Key takeaways

  • An outward spiral is an inward spiral numbered backwards.
  • n² + 1 − value swaps the first and last numbers.
  • With an odd n the 1 sits exactly in the centre.
  • Mark the primes in this layout and you get the Ulam spiral.

Reverse Spiral Matrix in C

#include <stdio.h>

int main(void) {
    int n = 5;
    int a[20][20] = {0};                    /* n can be up to 20 */
    int dr[] = {0, 1, 0, -1};                  /* right, down, left, up: clockwise */
    int dc[] = {1, 0, -1, 0};
    int r = 0, c = 0, d = 0;

    for (int value = 1; value <= n * n; value++) {
        a[r][c] = value;
        for (int turn = 0; turn < 4; turn++) {   /* find the next free cell */
            int nr = r + dr[d], nc = c + dc[d];
            if (nr >= 0 && nr < n && nc >= 0 && nc < n && a[nr][nc] == 0) {
                r = nr;
                c = nc;
                break;
            }
            d = (d + 1) % 4;
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            printf("%3d", n * n + 1 - a[i][j]);
        printf("\n");
    }
    return 0;
}

Reverse Spiral Matrix in C++

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main() {
    int n = 5;
    vector<vector<int>> a(n, vector<int>(n, 0));
    int dr[] = {0, 1, 0, -1};                  // right, down, left, up: clockwise
    int dc[] = {1, 0, -1, 0};
    int r = 0, c = 0, d = 0;

    for (int value = 1; value <= n * n; value++) {
        a[r][c] = value;
        for (int turn = 0; turn < 4; turn++) {   // find the next free cell
            int nr = r + dr[d], nc = c + dc[d];
            if (nr >= 0 && nr < n && nc >= 0 && nc < n && a[nr][nc] == 0) {
                r = nr;
                c = nc;
                break;
            }
            d = (d + 1) % 4;
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << setw(3) << n * n + 1 - a[i][j];
        cout << endl;
    }
    return 0;
}

Reverse Spiral Matrix in Java

public class ReverseSpiralMatrix {
    public static void main(String[] args) {
        int n = 5;
        int[][] a = new int[n][n];
        int[] dr = {0, 1, 0, -1};                  // right, down, left, up: clockwise
        int[] dc = {1, 0, -1, 0};
        int r = 0, c = 0, d = 0;

        for (int value = 1; value <= n * n; value++) {
            a[r][c] = value;
            for (int turn = 0; turn < 4; turn++) {   // find the next free cell
                int nr = r + dr[d], nc = c + dc[d];
                if (nr >= 0 && nr < n && nc >= 0 && nc < n && a[nr][nc] == 0) {
                    r = nr;
                    c = nc;
                    break;
                }
                d = (d + 1) % 4;
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.print(String.format("%3d", n * n + 1 - a[i][j]));
            System.out.println();
        }
    }
}

Reverse Spiral Matrix in Python

n = 5
a = [[0] * n for _ in range(n)]
dr = [0, 1, 0, -1]                          # right, down, left, up: clockwise
dc = [1, 0, -1, 0]
r = c = d = 0

for value in range(1, n * n + 1):
    a[r][c] = value
    for turn in range(4):              # find the next free cell
        nr, nc = r + dr[d], c + dc[d]
        if 0 <= nr < n and 0 <= nc < n and a[nr][nc] == 0:
            r, c = nr, nc
            break
        d = (d + 1) % 4

for i in range(n):
    for j in range(n):
        print(f"{n * n + 1 - a[i][j]:3d}", end="")
    print()

Time and space complexity

The grid has n² cells, each filled and printed once, so the program runs in O(n²) time with O(n²) memory.

Frequently asked questions

What happens with an even n?

The 1 lands in one of the four centre cells instead of the exact middle. The spiral is still correct; it just has no single centre cell.

Can I walk outwards from the centre directly?

Yes: move 1 step, turn, 1 step, turn, 2 steps, turn, 2 steps, and so on. That is how the spiral walk from a cell works. Reversing an inward spiral is shorter to write.

Which way does it turn?

Read from 1 outwards it turns anticlockwise: 1 → 2 is left, then down, right and up. That is the mirror of the clockwise inward walk.

This tutorial was drafted with AI assistance. Spotted a mistake? Tell us and we fix it. Read our editorial policy.

Quick check: can you predict the output?

Answer from the code, then check. Every answer comes from the real output above.

Pattern 5 of 14 in Spiral Patterns

 

Still stuck? Ask AI to explain this code

Opens your favourite AI with this page, ready to explain every loop step by step.

Authored by

Ghanendra Yadav runs Pattern Programs from Bangalore, India. The site started in 2020 to help students practise loops and logic through pattern programs in C, C++, Java and Python. Every program published here is compiled and run before it goes live, and the output shown is the real output.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.