Tutorialspoint
Problem
Solution
Submissions

Spiral Order Traversal of a Matrix

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to return all elements of a matrix in spiral order. Given an m x n matrix, return all elements of the matrix in spiral order, starting from the top-left corner and moving clockwise.

Example 1
  • Input: matrix = [
    [1,2,3],
    [4,5,6],
    [7,8,9]]
  • Output: [1,2,3,6,9,8,7,4,5]
  • Explanation:
    • Matrix:
       1 2 3
       4 5 6
       7 8 9
    • Spiral order: 1→2→3→6→9→8→7→4→5
Example 2
  • Input: matrix = [
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12]]
  • Output: [1,2,3,4,8,12,11,10,9,5,6,7]
  • Explanation:
    • Matrix:
       1 2 3 4
       5 6 7 8
       9 10 11 12
    • Spiral order: 1→2→3→4→8→12→11→10→9→5→6→7
Constraints
  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 10
  • -100 ≤ matrix[i][j] ≤ 100
  • Time Complexity: O(m*n)
  • Space Complexity: O(1) (excluding the output array)
ArraysMatrixTCS (Tata Consultancy Services)Snowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Define four boundaries: top, right, bottom, and left
  • Traverse the matrix in spiral order by processing one layer at a time
  • Update the boundaries after processing each side of the current layer
  • Be careful with the termination condition when the matrix is not square
  • Add each visited element to the result list

Steps to solve by this approach:

 Step 1: Initialize four boundary variables: top, right, bottom, and left.
 Step 2: Start a while loop that continues as long as top <= bottom and left <= right.
 Step 3: Traverse from left to right along the top row, then increment top.
 Step 4: Traverse from top to bottom along the rightmost column, then decrement right.
 Step 5: If there are rows remaining (top <= bottom), traverse from right to left along the bottom row, then decrement bottom.
 Step 6: If there are columns remaining (left <= right), traverse from bottom to top along the leftmost column, then increment left.
 Step 7: Continue this process until all elements have been visited.

Submitted Code :