AlgoMaster Logo

Spiral Matrix

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Simulation

Intuition:

The problem is about collecting numbers in a matrix in a defined "spiral order". We can simulate this process by keeping track of boundaries that govern the visible "layer" of the matrix being iterated upon. Initially, these boundaries correspond to the full extent of the matrix, and they contract as we pick up elements in spiral fashion.

We maintain four boundaries:

  • Top boundary: starts at the first row and moves downward.
  • Bottom boundary: starts at the last row and moves upward.
  • Left boundary: starts at the first column and moves rightward.
  • Right boundary: starts at the last column and moves leftward.

By traversing these boundaries in the correct sequence, we can extract the elements of the matrix in spiral order.

Steps:

  1. Traverse the top row from left boundary to right boundary, then move the top boundary downward.
  2. Traverse the right column from top boundary to bottom boundary, then move the right boundary leftward.
  3. Traverse the bottom row from right boundary to left boundary, then move the bottom boundary upward.
  4. Traverse the left column from bottom boundary to top boundary, then move the left boundary rightward.
  5. Repeat until all boundaries meet or cross each other.

Code:

2. Optimized

Intuition:

A more structured version of the basic approach relies on cycling through four directions: right, down, left, and up. We can simplify by using a direction index to manage changes in direction and move uniformly until a boundary condition stops us.

Steps:

  1. Define coordinates changes for directions: (0,1) for right, (1,0) for down, (0,-1) for left, (-1,0) for up.
  2. Use an index to rotate through these directions as necessary.
  3. For each movement action, validate if the destination is within unvisited cells.
  4. Adjust direction and mark cell as visited when hitting a boundary.

Code: