Spiral Matrix - Array - Medium - LeetCode
💻 coding

Spiral Matrix - Array - Medium - LeetCode

1 min read 134 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires returning elements of a matrix in spiral order.
  • 2The provided solution uses a while loop to traverse the matrix boundaries.
  • 3The time complexity of the solution is O(n^2) with O(1) space complexity.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires returning elements of a matrix in spiral order."

Spiral Matrix - Array - Medium - LeetCode

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5] Example 2:

Input: [ [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]

public class Solution {
 public IList<int> SpiralOrder(int[][] matrix) {
 
 var res = new List<int>();
 
 if(matrix.Length==0){
 return res;
 }
 
 int sx = 0;
 int ex = matrix.Length;
 int sy = 0;
 int ey = matrix[0].Length;
 
 
 while (sx<ex && sy<ey){
 for(int i=sy;i<ey;i++){
 res.Add(matrix[sx][i]);
 }
 sx++;
 
 for(int i= sx;i<ex;i++){
 res.Add(matrix[i][ey-1]);
 }
 ey--;
 
 if(sx<ex){
 for(int i= ey-1;i>=sy;i--){
 res.Add(matrix[ex-1][i]);
 }
 }
 ex--;
 
 if(sy<ey){
 for(int i=ex-1;i>=sx;i--){
 res.Add(matrix[i][sy]);
 }
 }
 sy++;
 }
 
 return res;
 }
}

Time Complexity: O(n^2)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 27 October 2020 · 1 min read · 134 words

Part of AskGif Blog · coding

You might also like