Member-only story

Leetcode 54: Spiral Matrix. Solution in Java

Pierre-Marie Poitevin
4 min readDec 15, 2021

--

In this problem, we need to go through an array in a spiral pattern, clockwise, starting from the “top-left” of the array, and return all the elements in the order you encounter them. This is a exact question statement:

Given an m x n matrix, return all elements of the matrix in spiral order.

Here are a few examples used for testing:

Examples

Other examples would be the empty array [[]], or an array with only one element [[1]], or arrays with only one row or column [[1],[2],[3],[4]].

Solution

Here is how we can solve the problem:

  • Initialize the current direction to “go right” at the start
  • Whenever we encounter a corner of the array, or anytime we need to change direction, we need to be able to tell with a simple test
  • We need to be able to change direction when needed and simply iterate towards the new direction, and continue until we explored all the elements in the array

Initialization

Simply start by initializing the result, the initial position, and the initial direction:

List<Integer> res = new ArrayList<>();
int x = 0;
int y = 0;
// initialize (go right)
int incX = 0;
int incY = 1;

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet