Traversing Diagonally in a matrix in JavaScript

In JavaScript, traversing a matrix diagonally means moving through the elements in a zigzag pattern from top-left to bottom-right. This technique is useful for various algorithms including matrix processing and image manipulation.

Problem Statement

We need to write a JavaScript function that takes a square matrix (array of arrays with equal rows and columns) and traverses it diagonally, creating a new array with elements in the order they were encountered.

For example, given this input matrix:

const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

The diagonal traversal should produce:

const output = [1, 2, 4, 7, 5, 3, 6, 8, 9];

Visual Representation

1 2 3 4 5 6 7 8 9 Diagonal Traversal Order: 1 ? 2 ? 4 ? 7 ? 5 ? 3 ? 6 ? 8 ? 9

Implementation

const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

const findDiagonalOrder = (arr = []) => {
    if (!arr.length) {
        return [];
    }
    
    let ind = 0;
    let colBegin = 0, rowBegin = 0;
    let rowMax = arr.length, colMax = arr[0].length;
    const res = [], stack = [];
    
    while (rowBegin < rowMax || colBegin < colMax) {
        // Traverse current diagonal
        for (let row = rowBegin, col = colBegin; row < rowMax && col >= 0; row++, col--) {
            if (ind % 2 === 0) {
                // Even diagonal: use stack to reverse order
                stack.push(arr[row][col]);
            } else {
                // Odd diagonal: direct order
                res.push(arr[row][col]);
            }
        }
        
        ind++;
        
        // Empty stack to result array
        while (stack.length) {
            res.push(stack.pop());
        }
        
        colBegin++;
        
        // Switch to next row when column boundary reached
        if (colBegin > colMax - 1 && rowBegin < rowMax) {
            colBegin = colMax - 1;
            rowBegin++;
        }
    }
    
    return res;
};

console.log(findDiagonalOrder(arr));
[
  1, 2, 4, 7, 5,
  3, 6, 8, 9
]

How It Works

The algorithm works by:

  • Diagonal Identification: Each diagonal is traversed from top-right to bottom-left direction
  • Direction Alternation: Even-indexed diagonals are reversed using a stack, odd-indexed diagonals maintain natural order
  • Boundary Handling: The algorithm switches between incrementing column start and row start positions
  • Stack Usage: A stack reverses the order of elements in even diagonals to achieve the zigzag pattern

Alternative Simple Implementation

const simpleDiagonalTraversal = (matrix) => {
    const result = [];
    const rows = matrix.length;
    const cols = matrix[0].length;
    
    // Process all diagonals
    for (let d = 0; d < rows + cols - 1; d++) {
        const diagonal = [];
        
        // Find starting point for current diagonal
        const startRow = d < cols ? 0 : d - cols + 1;
        const startCol = d < cols ? d : cols - 1;
        
        // Collect elements in current diagonal
        for (let r = startRow, c = startCol; r < rows && c >= 0; r++, c--) {
            diagonal.push(matrix[r][c]);
        }
        
        // Reverse every other diagonal for zigzag pattern
        if (d % 2 === 1) {
            diagonal.reverse();
        }
        
        result.push(...diagonal);
    }
    
    return result;
};

const testMatrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
];

console.log(simpleDiagonalTraversal(testMatrix));
[
  1,  2,  5,  9,
  6,  3,  4,  7,
  10, 11, 8, 12
]

Conclusion

Diagonal matrix traversal creates a zigzag pattern useful in various algorithms. The key is alternating direction for each diagonal using either a stack or array reversal to achieve the desired output order.

Updated on: 2026-03-15T23:19:00+05:30

946 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements