Leetcode Problem 59. Spiral Matrix II

59. Spiral Matrix II

Leetcode Solutions

Traverse Layer by Layer in Spiral Form

  1. Initialize a 2D array matrix of size n x n with all elements set to 0.
  2. Set the starting number num to 1.
  3. Define the boundaries of the current layer: top, bottom, left, and right.
  4. While num is less than or equal to n^2, repeat the following steps: a. Traverse from left to right along the top row and fill the cells with num. b. Increment top to move to the next inner layer. c. Traverse from top to bottom along the right column and fill the cells with num. d. Decrement right to narrow the layer. e. Traverse from right to left along the bottom row and fill the cells with num. f. Decrement bottom to move to the next inner layer. g. Traverse from bottom to top along the left column and fill the cells with num. h. Increment left to narrow the layer.
  5. Return the filled matrix.
UML Thumbnail

Optimized Spiral Traversal

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...