FastPrepSpiral Matrix Traversal
Problem · Matrix

Spiral Matrix Traversal

Learn this problem
MediumAmazon logoAmazonNEW GRADONSITE INTERVIEW
See Amazon 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.

Example 3

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]clockwise = truereturn = [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]

Exercises two complete clockwise rings and the inner two-by-two boundary.

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