| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.SpiralMatrix; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SpiralMatrixSimulation : ISpiralMatrix |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n * m) |
| | 19 | | /// Space complexity - O(n * m) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="matrix"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public IList<int> SpiralOrder(int[][] matrix) |
| 2 | 24 | | { |
| 2 | 25 | | var rows = matrix.Length; |
| 2 | 26 | | var columns = matrix[0].Length; |
| | 27 | |
|
| 2 | 28 | | var spiralMatrix = new int[rows * columns]; |
| 2 | 29 | | var spiralMatrixIndex = 0; |
| | 30 | |
|
| 2 | 31 | | var left = 0; |
| 2 | 32 | | var top = 0; |
| 2 | 33 | | var right = columns - 1; |
| 2 | 34 | | var bottom = rows - 1; |
| | 35 | |
|
| 6 | 36 | | while (top <= bottom && left <= right) |
| 4 | 37 | | { |
| 28 | 38 | | for (var j = left; j <= right; j++) |
| 10 | 39 | | { |
| 10 | 40 | | spiralMatrix[spiralMatrixIndex] = matrix[top][j]; |
| | 41 | |
|
| 10 | 42 | | spiralMatrixIndex++; |
| 10 | 43 | | } |
| | 44 | |
|
| 4 | 45 | | top++; |
| | 46 | |
|
| 16 | 47 | | for (var i = top; i <= bottom; i++) |
| 4 | 48 | | { |
| 4 | 49 | | spiralMatrix[spiralMatrixIndex] = matrix[i][right]; |
| | 50 | |
|
| 4 | 51 | | spiralMatrixIndex++; |
| 4 | 52 | | } |
| | 53 | |
|
| 4 | 54 | | right--; |
| | 55 | |
|
| 4 | 56 | | if (top <= bottom) |
| 2 | 57 | | { |
| 14 | 58 | | for (var j = right; j >= left; j--) |
| 5 | 59 | | { |
| 5 | 60 | | spiralMatrix[spiralMatrixIndex] = matrix[bottom][j]; |
| | 61 | |
|
| 5 | 62 | | spiralMatrixIndex++; |
| 5 | 63 | | } |
| | 64 | |
|
| 2 | 65 | | bottom--; |
| 2 | 66 | | } |
| | 67 | |
|
| 4 | 68 | | if (left <= right) |
| 3 | 69 | | { |
| 10 | 70 | | for (var i = bottom; i >= top; i--) |
| 2 | 71 | | { |
| 2 | 72 | | spiralMatrix[spiralMatrixIndex] = matrix[i][left]; |
| | 73 | |
|
| 2 | 74 | | spiralMatrixIndex++; |
| 2 | 75 | | } |
| | 76 | |
|
| 3 | 77 | | left++; |
| 3 | 78 | | } |
| 4 | 79 | | } |
| | 80 | |
|
| 2 | 81 | | return spiralMatrix; |
| 2 | 82 | | } |
| | 83 | | } |