Problem: Given a 2D array, print it in spiral form.
Example:
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]
Approach: Nothing to explain, just for loops. Have a look at implementation directly.
Implementation in C#:
public IList<int> SpiralOrder(int[][] matrix)
{
List<int> result = new List<int>();
int rows = matrix?.Length ?? 0;
if (rows == 0)
{
return result;
}
int cols = matrix[0].Length;
int startRow = 0, endRow = rows - 1;
int startCol = 0, endCol = cols - 1;
while (startRow <= endRow && startCol <= endCol)
{
for (int i = startCol; i <= endCol; ++i)
{
result.Add(matrix[startRow][i]);
}
for (int i = startRow + 1; i <= endRow; ++i)
{
result.Add(matrix[i][endCol]);
}
if (startRow < endRow && startCol < endCol)
{
for (int i = endCol - 1; i >= startCol; --i)
{
result.Add(matrix[endRow][i]);
}
for (int i = endRow - 1; i > startRow; --i)
{
result.Add(matrix[i][startCol]);
}
}
++startRow;
--endRow;
++startCol;
--endCol;
}
return result;
}
Complexity: O(row*col)
No comments:
Post a Comment