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

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.
- For each sum
sfrom 0 to2n − 2: - if
sis odd, letirun from 0 up tos; if even, fromsdown to 0. - For each
iwhere bothiands − iare inside the grid, write the next number intoa[i][s − i]. - 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.






