Hard code col and row counts is not good
int colRight = 2;
int colLeft = 0;
int rowTop = 0;
int rowEnd = 2;
Test method should print out results - not method
I think this will fail if the matrix is not square
if (colRight == colLeft && rowTop == rowEnd)
I think this is cleaner
public static void TestSpiralPrint()
{
int[,] matrix = new int[5, 4];
matrix[0, 0] = 1; matrix[0, 1] = 2; matrix[0, 2] = 3; matrix[0, 3] = 4;
matrix[1, 0] = 5; matrix[1, 1] = 6; matrix[1, 2] = 7; matrix[1, 3] = 8;
matrix[2, 0] = 9; matrix[2, 1] = 10; matrix[2, 2] = 11; matrix[2, 3] = 12;
matrix[3, 0] = 13; matrix[3, 1] = 14; matrix[3, 2] = 15; matrix[3, 3] = 16;
matrix[4, 0] = 17; matrix[4, 1] = 18; matrix[4, 2] = 19; matrix[4, 3] = 20;
List<int> output = SpiralPrint(matrix);
foreach (int i in output)
Debug.WriteLine(i);
Debug.WriteLine("");
}
private static List<int> SpiralPrint(int[,] matrix)
{
List<int> output = new List<int>();
if (matrix != null && matrix.Length > 0)
{
int top = 0;
int btm = matrix.GetLength(0);
int lft = 0;
int rht = matrix.GetLength(1);
while (lft < rht && top < btm)
{
for (int i = lft; i < rht; i++)
output.Add(matrix[top, i]);
top++;
for (int i = top; i < btm; i++)
output.Add(matrix[i, rht - 1]);
rht--;
if (lft < rht)
{
for (int i = rht - 1; i >= lft; i--)
output.Add(matrix[btm - 1, i]);
btm--;
}
if (top < btm)
{
for (int i = btm - 1; i >= top; i--)
output.Add(matrix[i, lft]);
lft++;
}
}
}
return output;
}