Problem · Matrix

Spiral Matrix Traversal

Learn this problem
MediumMicrosoft logoMicrosoftFULLTIMEONSITE INTERVIEW
See Microsoft hiring insights

Problem statement

Given a non-empty rectangular integer matrix matrix and a boolean clockwise, return all values in spiral order.

  • When clockwise is true, start at the top-left cell and initially move right.
  • When clockwise is false, start at the top-left cell and initially move down.
  • Visit every cell exactly once.

Function

spiralOrder(matrix: int[][], clockwise: boolean) → int[]

Examples

Example 1

matrix = [[1,2,3],[4,5,6],[7,8,9]]clockwise = truereturn = [1,2,3,6,9,8,7,4,5]

The traversal follows the top row, right edge, bottom row, left edge, and then the center.

Example 2

matrix = [[1,2,3,4,5]]clockwise = falsereturn = [1,2,3,4,5]

A single row has only one possible visit order from the top-left cell.

Constraints

  • matrix has at least one row and one column.
  • Every row has the same number of columns.
  • Every matrix value is a signed integer.

More Microsoft problems

drafts saved locally
public int[] spiralOrder(int[][] matrix, boolean clockwise) {
    // TODO: return every matrix value in the requested spiral order.
}
matrix[[1,2,3],[4,5,6],[7,8,9]]
clockwisetrue
expected[1,2,3,6,9,8,7,4,5]
checking account