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

Zig-Zag Diagonal Matrix Fill

The zig-zag diagonal matrix numbers a grid along its diagonals, going down one diagonal and up the next. It is the order JPEG image compression uses to read an 8 × 8 block, and the idea behind LeetCode 498, “Diagonal Traverse”.

Quick answer: Every cell on one diagonal has the same i + j. Loop over these sums s from 0 to 2n − 2. On odd diagonals walk downwards (row increasing) and on even ones walk upwards, numbering each cell that is inside the grid.

This program is part of the Wave Patterns collection.

Table of contents8 sections
  1. Output
  2. How the zig-zag diagonal matrix fill 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

Zig-Zag Diagonal Matrix Fill output

Output (n = 4):

  1  2  6  7
  3  5  8 13
  4  9 12 14
 10 11 15 16
Zig-Zag Diagonal Matrix Fill layout diagram, row by row (n = 4)
The numbers of the zig-zag diagonal matrix fill laid out row by row (n = 4).

How the zig-zag diagonal matrix fill works

The diagonals that run from top right to bottom left each have a constant i + j. Visiting them in order of that sum covers the whole grid. The zig-zag comes from changing direction on every diagonal: odd sums go from the top row down, even sums from the bottom up. The checks i < n and s − i < n skip the parts of the long diagonals that fall outside the grid.

  1. For each sum s from 0 to 2n − 2:
  2. if s is odd, let i run from 0 up to s; if even, from s down to 0.
  3. For each i where both i and s − i are inside the grid, write the next number into a[i][s − i].
  4. Print the grid row by row.

Key takeaways

  • A diagonal is the set of cells with the same i + j.
  • Changing direction on every diagonal makes the zig-zag.
  • Bounds checks skip the parts of long diagonals that leave the grid.
  • JPEG reads image blocks in exactly this order.

Zig-Zag Diagonal Matrix Fill in C

#include <stdio.h>

int main(void) {
    int n = 4;
    int a[20][20];
    int value = 1;

    for (int s = 0; s <= 2 * (n - 1); s++) {        /* i + j is the same on every cell of a diagonal */
        if (s % 2 == 1) {                           /* odd diagonals run downwards */
            for (int i = 0; i <= s; i++)
                if (i < n && s - i < n)
                    a[i][s - i] = value++;
        } else {                                    /* even diagonals run upwards */
            for (int i = s; i >= 0; i--)
                if (i < n && s - i < n)
                    a[i][s - i] = value++;
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            printf("%3d", a[i][j]);
        printf("\n");
    }
    return 0;
}

Zig-Zag Diagonal Matrix Fill in C++

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

int main() {
    int n = 4;
    vector<vector<int>> a(n, vector<int>(n));
    int value = 1;

    for (int s = 0; s <= 2 * (n - 1); s++) {        // i + j is the same on every cell of a diagonal
        if (s % 2 == 1) {                           // odd diagonals run downwards
            for (int i = 0; i <= s; i++)
                if (i < n && s - i < n)
                    a[i][s - i] = value++;
        } else {                                    // even diagonals run upwards
            for (int i = s; i >= 0; i--)
                if (i < n && s - i < n)
                    a[i][s - i] = value++;
        }
    }
    for (auto &row : a) {
        for (int x : row)
            cout << setw(3) << x;
        cout << endl;
    }
    return 0;
}

Zig-Zag Diagonal Matrix Fill in Java

public class ZigzagDiagonalMatrix {
    public static void main(String[] args) {
        int n = 4;
        int[][] a = new int[n][n];
        int value = 1;

        for (int s = 0; s <= 2 * (n - 1); s++) {        // i + j is the same on every cell of a diagonal
            if (s % 2 == 1) {                           // odd diagonals run downwards
                for (int i = 0; i <= s; i++)
                    if (i < n && s - i < n)
                        a[i][s - i] = value++;
            } else {                                    // even diagonals run upwards
                for (int i = s; i >= 0; i--)
                    if (i < n && s - i < n)
                        a[i][s - i] = value++;
            }
        }
        for (int[] row : a) {
            for (int x : row)
                System.out.printf("%3d", x);
            System.out.println();
        }
    }
}

Zig-Zag Diagonal Matrix Fill in Python

n = 4
a = [[0] * n for _ in range(n)]
value = 1

for s in range(2 * n - 1):                      # i + j is the same on every cell of a diagonal
    rows = range(s + 1) if s % 2 == 1 else range(s, -1, -1)   # odd: downwards, even: upwards
    for i in rows:
        if i < n and s - i < n:
            a[i][s - i] = value
            value += 1
for row in a:
    print("".join(f"{x:3d}" for x in row))

Time and space complexity

Each cell is filled once, but the inner loops also skip some positions outside the grid, which is still O(n²) in total. The grid uses O(n²) memory.

Frequently asked questions

How do I print the order as a list instead (LeetCode 498)?

Fill a real matrix first, then run the same loops and print a[i][s − i] instead of writing to it. For a 3 × 3 grid of 1 to 9 the result is 1 2 4 7 5 3 6 8 9.

Why does JPEG use this order?

After the image block is transformed, the important values sit in the top-left corner. Reading in zig-zag order puts them first and groups the many zeros at the end, which compresses well.

Does it work for rectangles?

Yes. Use separate row and column counts in the bounds checks and run s up to rows + cols − 2.

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 12 in Wave 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.