DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk5 min

How to Trace a Matrix in Clockwise Spiral Order, Step by Step

Trace a matrix clockwise without skipping or repeating cells. See the shrinking-boundaries method, a JavaScript implementation, and how to handle one-row or one-column leftovers.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To traverse a rectangular matrix in clockwise spiral order, start at the upper-left cell, move right across the top row, then down the right edge, left across the bottom row, and up the left edge. Repeat on the smaller rectangle left inside. The key to avoiding duplicates is to shrink the boundaries after each edge and check that the remaining row or column still exists before traversing it.

What does spiral order mean?

LeetCode problem 54 asks you to “return all elements of the matrix in spiral order.” The traversal begins at the upper-left and follows the outside perimeter clockwise before moving inward. For a nonempty rectangular matrix with m rows and n columns, the output contains exactly m × n elements. The problem’s stated constraints are 1 ≤ m, n ≤ 10 and -100 ≤ matrix[i][j] ≤ 100 (LeetCode, Spiral Matrix).

As an Amazon Associate I earn from qualifying purchases.

Example: a 3 × 3 matrix

For [[1,2,3],[4,5,6],[7,8,9]], read the perimeter first, then the center:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
[1, 2, 3, 6, 9, 8, 7, 4, 5]

Example: a 3 × 4 matrix

For [[1,2,3,4],[5,6,7,8],[9,10,11,12]], the spiral order is:

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

How to trace the traversal one step at a time

A scrub-through visualizer can make the boundary method easy to follow. The visualizer described here is a trace specification, not a claim about a particular tested tool: each step should identify the current cell and direction, show the unvisited rectangle’s boundaries, and add the cell’s value to the output.

  1. Initialize: set top = 0, bottom = m - 1, left = 0, and right = n - 1. Start with an empty output.
  2. Move right: visit cells in row top, from column left through right. Then move top down by one.
  3. Check for remaining rows: if top > bottom, stop. Otherwise, move down column right, from row top through bottom, then move right left by one.
  4. Check for remaining columns: if left > right, stop. Otherwise, move left across row bottom, from column right down through left, then move bottom up by one.
  5. Check for remaining rows again: if top > bottom, stop. Otherwise, move up column left, from row bottom up through top, then move left right by one.
  6. Repeat: continue while top ≤ bottom and left ≤ right.

For a useful scrubber, make the active edge visually distinct, mark each visited cell, and update the four boundary values after the edge finishes. Display the output list alongside the matrix so a reader can match every move to its appended value. At the end, the list should contain m × n entries.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Boundary-shrinking implementation

This implementation follows the trace directly. Its crossed-bound checks matter: after the top row or right column has been consumed, the remaining region might be only one row or one column. Traversing a bottom or left edge without checking can visit cells a second time.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function spiralOrder(matrix) {
  const m = matrix.length;
  const n = matrix[0].length;
  const result = [];
  let top = 0;
  let bottom = m - 1;
  let left = 0;
  let right = n - 1;

  while (top <= bottom && left <= right) {
    for (let col = left; col <= right; col++) {
      result.push(matrix[top][col]);
    }
    top++;

    if (top > bottom) break;
    for (let row = top; row <= bottom; row++) {
      result.push(matrix[row][right]);
    }
    right--;

    if (left > right) break;
    for (let col = right; col >= left; col--) {
      result.push(matrix[bottom][col]);
    }
    bottom--;

    if (top > bottom) break;
    for (let row = bottom; row >= top; row--) {
      result.push(matrix[row][left]);
    }
    left++;
  }

  return result;
}

The snippet assumes a nonempty rectangular matrix, matching LeetCode 54’s stated constraints. The four bounds describe the as-yet-unvisited rectangle; they are not indices that should be reset when a lap ends. A boundary-method hint and caution about one-row and one-column cases appear in the LeetCode community discussion.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Why the checks prevent repeats

  • If the top row was the last row, incrementing top crosses bottom; there is no right edge left to traverse.
  • If the right column was the last column, decrementing right crosses left; there is no bottom edge left to traverse.
  • After the bottom edge is consumed, its boundary moves inward. The final check ensures there is still a row for the upward pass.

Alternative: simulate direction with a visited grid

Instead of shrinking a rectangle, track the current (row, column) and one of four directions. Visit exactly m × n cells. After each visit, inspect the next cell: if it is outside the matrix or already visited, rotate clockwise and move in the new direction. A separate visited grid makes the stopping rule explicit and leaves the input values unchanged. The cited LeetCode Wiki (Doocs) implementation gives this approach O(mn) time and O(mn) auxiliary space (LeetCode Wiki (Doocs), 54. Spiral Matrix).

Which traversal model should you use?

Question Shrinking boundaries Direction simulation
How is the path represented? Four edges of the unvisited rectangle Current cell and one of four directions
How are repeats avoided? Move bounds inward and check for crossed bounds before later edges Turn when the next cell is out of bounds or already visited
Extra memory established by the cited material No like-for-like complexity figure is established in the cited sources O(mn) auxiliary space for the visited grid
Does traversal require changing input values? The boundary method reads values and appends them; it does not need to change the matrix A separate visited grid avoids changing matrix values
Visual explanation Shows the unvisited rectangle contracting after each edge Shows the next move, turns, and visited cells

Choose shrinking boundaries when you want to explain the perimeter-and-inward pattern. Choose a visited-grid simulation when making each turn and the exact number of visits explicit is more useful. These are two models of the same clockwise order.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How to handle a single row or column

These cases expose the boundary method’s main duplicate-visit risk. A single-row matrix is exhausted by the first left-to-right pass; a single-column matrix is exhausted by the top-to-bottom pass. The crossed-bound checks stop later passes from adding those cells again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • [[1,2,3]] produces [1,2,3].
  • [[1],[2],[3]] produces [1,2,3].
  • [[1]] produces [1].

How to check an implementation

Before accepting a traversal, verify it against the matrix’s shape as well as its values:

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
  • The output length is m × n.
  • Every cell is appended once, including when the last unvisited region is a single row, column, or cell.
  • The first pass starts at the upper-left and moves right; each completed turn is clockwise.
  • The input matrix remains unchanged if your implementation uses a separate output and visited grid or only reads values.

A tempting shortcut is to mark visited cells by changing their values. One cited variant adds 300 to mark a cell, relying on LeetCode 54’s value bounds of -100 through 100. That assumption is specific to those constraints, alters the matrix during traversal, and is not a general-purpose marking strategy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.