https://leetcode.com/problems/spiral-matrix-ii/ Please review for performance, how can this code run faster
Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
/// <summary>
/// https://leetcode.com/problems/spiral-matrix-ii/
/// </summary>
[TestClass]
public class SpiralMatrix2Test
{
[TestMethod]
public void Example3x3Test()
{
int size = 3;
int[][] expected =
{
new[]{1,2,3},
new [] {8,9,4},
new []{7,6,5}
};
int[][] res= SpiralMatrix2.GenerateMatrix(size);
for (int i = 0; i < size; i++)
{
CollectionAssert.AreEqual(expected[i],res[i]);
}
}
}
public class SpiralMatrix2
{
public static int[][] GenerateMatrix(int n)
{
int startCol = 0;
int endCol = n - 1;
int startRow = 0;
int endRow = n - 1;
int num = 1;
int[][] res = new int[n][];
for (int i = 0; i < n; i++)
{
res[i] = new int[n];
}
if (n == 0)
{
return res;
}
while (startCol <= endCol && startRow <= endRow)
{
for (int i = startCol; i <= endCol; i++)
{
res[startRow][i] = num++;
}
startRow++;// already did this row skip to the next one
for (int i = startRow; i <= endRow; i++)
{
res[i][endCol] = num++;
}
endCol--;// already did the last col move back one col
for (int i = endCol; i >= startCol; i--)
{
//keep in mind this is a spiral we can be in a line we are not suppose to touch the values
//only in the upper half of the matrix we need
if (startRow <= endRow)
{
res[endRow][i] = num++;
}
}
endRow--;
for (int i = endRow; i >= startRow; i--)
{
//we need to print the numbers only in the left half of the matrix
if (startCol <= endCol)
{
res[i][startCol] = num++;
}
}
startCol++;
}
return res;
}
}
}