Free beta: 30 days of full access, no card needed.Sign up free

We use necessary cookies to run the site (sign-in and language). The contact and bug-report forms also use Google reCAPTCHA for spam protection, loaded only if you accept. Privacy policy

Field manual

Matrix traversal (spiral / diagonal)

O(mn)

Walk a grid layer by layer (spiral) or diagonal by diagonal, pulling the boundary in after each pass. The same coordinate math rotates a grid 90 degrees without a spiral at all.

Signals

read or fill a grid in spiral orderwalk a matrix diagonal by diagonalrotate a matrix 90 degreesvisit every cell in a fixed geometric order

Template

function spiralOrder(matrix) {
    const result = [];
    let top = 0, bottom = matrix.length - 1;
    let left = 0, right = matrix[0].length - 1;
    while (top <= bottom && left <= right) {
        for (let c = left; c <= right; c++) result.push(matrix[top][c]);
        for (let r = top + 1; r <= bottom; r++) result.push(matrix[r][right]);
        if (top < bottom) for (let c = right - 1; c >= left; c--) result.push(matrix[bottom][c]);
        if (left < right) for (let r = bottom - 1; r > top; r--) result.push(matrix[r][left]);
        top++; bottom--; left++; right--;
    }
    return result;
}

Looks similar, isn't

  • Matrix search (sorted grid): A spiral or diagonal walk visits every cell in some fixed geometric order because the task is to read or transform the whole grid. Matrix search instead exploits that rows and columns are already sorted, dropping a row or column at each step to find one value without touching most of the grid.

grid up to ~1e3 x 1e3 cells, each cell visited exactly once -> O(m*n): a spiral, diagonal, or rotation touches every cell one time.

Learn this pattern