Matrix in spiral
A quick one this time. Given a matrix, print the elements in a spiral starting from the upper left corner and going right, down, left, up and so on.
I find this picture from Bees & Bombs inspiring.
I'm using four indexes representing the current step four corners. They will update depending on the direction. Here is the code:
public static IEnumerable<T> Traverse<T>(T[,] matrix, int width, int height) { int iStart = 0; int iEnd = width - 1; int jStart = 0; int jEnd = height - 1; int direction = 0; while (iStart <= iEnd && jStart <= jEnd) { if (direction == 0) { for (int j = jStart; j <= jEnd; j++) { yield return matrix[iStart, j]; } iStart++; } else if (direction == 1) { for (int i = iStart; i <= iEnd; i++) { yield return matrix[i, jEnd]; } jEnd--; } else if (direction == 2) { for (int j = jEnd; j >= jStart; j--) { yield return matrix[iEnd, j]; } iEnd--; } else { for (int i = iEnd; i >= iStart; i--) { yield return matrix[i, jStart]; } jStart++; } direction = ++direction % 4; } }
With an example:
var matrix = new[,] { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; MatrixInSpiral.Traverse(matrix, 4, 5).ToList().ForEach(x => Console.Write("{0} ", x));
1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12














