Traverse Matrix in Diagonal strips
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Traversing a matrix in diagonal strips is a unique method that involves accessing the elements of the matrix along its diagonal paths. This technique can be particularly useful in various computational tasks, such as image processing, numerical analysis, and certain types of algorithms like the SVD (Singular Value Decomposition) where diagonal focus is beneficial. This article delves into the technical explanation of matrix diagonal traversal, illustrated with examples and summarized in a table format for easier understanding.
Technical Explanation
A matrix is a two-dimensional array of numbers. In this context, a diagonal refers to a set of elements of the matrix that are aligned at differing indices for rows (`i`) and columns (`j`) in a consistent manner. Mathematically, the diagonal can be represented as elements that satisfy the condition `i - j = c`, where `c` is a constant that defines a particular diagonal.
Traversal Method
When traversing diagonally, we can consider two main types:
- Main Diagonal Traversal: This includes elements where `i - j = 0`, i.e., the principal diagonal.
- Anti-Diagonal Traversal: This incorporates diagonals parallel to the main diagonal, either above (`i - j > 0`) or below it (`i - j < 0`).
The traversal starts either from the top-left corner or from the top-right corner, depending on whether traversal is from the main diagonal or anti-diagonally. The key is incrementally adjusting row (`i`) and column (`j`) indices to maintain either `i + j = constant` (anti-diagonal) or `i - j = constant` (main diagonal).
Example
Consider the following 3x3 matrix:
- `i - j = 0`: 1, 5, 9
- `i - j = 1`: 4, 8
- `i - j = 2`: 7
- `i - j = -1`: 2, 6
- `i - j = -2`: 3
- `i + j = 0`: 1
- `i + j = 1`: 2, 4
- `i + j = 2`: 3, 5, 7
- `i + j = 3`: 6, 8
- `i + j = 4`: 9
- Image Processing: Diagonal traversing can efficiently compute spatial features, preserve correlations along diagonals, and reduce computation cost.
- Matrix Operations: Operations like determinant finding and matrix invertibility tests can leverage diagonal traversal for optimized operations.
- Algorithm Efficiency: Algorithms requiring examination of element relationships beyond direct neighbors can benefit from diagonal traversal, especially in dense matrices.
Related reading

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.