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

Anticlockwise Spiral Matrix

The anticlockwise spiral matrix fills the numbers 1 to 16 in a spiral that runs the other way from the clockwise spiral: down the left side first, then along the bottom, up the right side and back along the top, winding inwards.

Quick answer: Walk through the grid and write the numbers 1 to n² as you go. Start in the top-left corner moving down. Whenever the next cell is outside the grid or already filled, turn to the next direction in the order down, right, up, left.

This program is part of the Spiral Patterns collection.

Table of contents8 sections
  1. Output
  2. How the anticlockwise spiral matrix works
  3. Program in C
  4. Program in C++
  5. Program in Java
  6. Program in Python
  7. Time and space complexity
  8. Frequently asked questions

Anticlockwise Spiral Matrix output

Output (n = 4):

  1 12 11 10
  2 13 16  9
  3 14 15  8
  4  5  6  7
Anticlockwise Spiral Matrix layout diagram, row by row (n = 4)
The numbers of the anticlockwise spiral matrix laid out row by row (n = 4).

How the anticlockwise spiral matrix works

Instead of four boundary variables, this version simply walks. Two small arrays, dr and dc, hold how the row and column change for each direction. After writing a number, the program looks one cell ahead; if that cell is blocked it turns to the next direction. Changing the order of the directions is all it takes to switch between clockwise and anticlockwise.

  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. When every value is placed, print the grid row by row.

Key takeaways

  • The walk turns whenever the next cell is blocked.
  • Direction arrays dr and dc replace four separate loops.
  • Down, right, up, left gives an anticlockwise spiral; right, down, left, up gives a clockwise one.
  • The last number, n², always lands near the centre.

Anticlockwise Spiral Matrix in C

#include <stdio.h>

int main(void) {
    int n = 4;
    int a[20][20] = {0};                    /* n can be up to 20 */
    int dr[] = {1, 0, -1, 0};                  /* down, right, up, left: anticlockwise */
    int dc[] = {0, 1, 0, -1};
    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", a[i][j]);
        printf("\n");
    }
    return 0;
}

Anticlockwise Spiral Matrix in C++

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

int main() {
    int n = 4;
    vector<vector<int>> a(n, vector<int>(n, 0));
    int dr[] = {1, 0, -1, 0};                  // down, right, up, left: anticlockwise
    int dc[] = {0, 1, 0, -1};
    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) << a[i][j];
        cout << endl;
    }
    return 0;
}

Anticlockwise Spiral Matrix in Java

public class AnticlockwiseSpiralMatrix {
    public static void main(String[] args) {
        int n = 4;
        int[][] a = new int[n][n];
        int[] dr = {1, 0, -1, 0};                  // down, right, up, left: anticlockwise
        int[] dc = {0, 1, 0, -1};
        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", a[i][j]));
            System.out.println();
        }
    }
}

Anticlockwise Spiral Matrix in Python

n = 4
a = [[0] * n for _ in range(n)]
dr = [1, 0, -1, 0]                          # down, right, up, left: anticlockwise
dc = [0, 1, 0, -1]
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"{a[i][j]:3d}", end="")
    print()

Time and space complexity

Each cell is filled once and the turn check costs at most four tries, so the program runs in O(n²) time. The grid takes O(n²) memory.

Frequently asked questions

How do I make it clockwise?

Use the order right, down, left, up: dr = {0, 1, 0, -1} and dc = {1, 0, -1, 0}. That prints the spiral number matrix.

Why does the C version use a 20 × 20 array?

A fixed size lets the array start filled with zeros using = {0}. The program only uses the first n rows and columns, so any n up to 20 works.

Does it work for rectangles?

Yes, with separate row and column limits in the “is the next cell inside” test. The turning rule stays the same.

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 4 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.