Spiral Matrix

Try to solve the Spiral Matrix problem.

Statement#

Given an m×nm\times n matrix, return an array containing the matrix elements in spiral order, starting from the top-left cell.

Constraints:

  • 11\leq matrix.length 10\leq 10
  • 11\leq matrix[i].length 10\leq 10
  • 100-100\leq matrix[i][j] 100\leq 100

Examples#

Created with Fabric.js 3.6.6 Sample Example 1 -----------------------------------------------------------------------

1 of 3

Created with Fabric.js 3.6.6 Sample Example 2 -----------------------------------------------------------------------

2 of 3

Created with Fabric.js 3.6.6 Sample Example 3 -----------------------------------------------------------------------

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Spiral Matrix

1

What is the output if the following matrix is given as input?

matrix = [[2, 6, 8],
                  [3, 4, 8],
                  [9, 8, 8]]

A)

[2, 6, 8, 3, 4, 8, 9, 8, 8]

B)

[2, 6, 8, 8, 8, 8, 9, 3, 4]

C)

[2, 6, 8, 8, 4, 3, 9, 8, 8]

D)

[8, 6, 2, 3, 9, 8, 8, 8, 4]

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Declare a variable, direction, which stores either 11 (for going left → right and top → bottom) or 1-1 (for going right → left and bottom → top). Declare two variables, row and col (both initialized to 00), to keep track of the current indexes of the matrix.

Start traversing the matrix from the top-left cell.

Move horizontally across a row by adding direction to the col variable while keeping row unchanged. Add matrix[row][col] to the result array.

Move vertically across a column by adding direction to the row variable while keeping col unchanged. Add matrix[row][col] to the result array.

Flip the direction by multiplying the direction variable by 1-1.

Repeat this process until all cells have been traversed.


Try it yourself#

Implement your solution in the following coding playground:

Python
usercode > main.py
Input #1
Spiral Matrix

Matrices: Introduction

Solution: Spiral Matrix