1. Spiral Traversal of a 2D matrix
Problem:
Given a 2D matrix, traverse all it’s elements in a spiral form.
Referring the below matrix as an input (Red line shows a spiral traversal),
output should be: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Solution:
This implementation is done using C#.NET. Rectangular Matrix is declared using int[,] syntax.
public void DoSpiralTraversal(int[, ]rectArray) { if (rectArray != null && rectArray.Length > 0) { Console.WriteLine("Doing Spiral Traversal on a 2D array:"); int noOfElementsTraversed = 0, row_LB = 0, row_UB = rectArray.GetUpperBound(0), col_LB = 0, col_UB = rectArray.GetUpperBound(1), iter; while (noOfElementsTraversed = row_LB; iter–) { Console.Write(rectArray[iter, col_UB] + ” “); noOfElementsTraversed++; } if (noOfElementsTraversed == rectArray.Length) { break; } col_UB–-; // Move right to Left for (iter = col_UB; iter >= col_LB; iter–) { Console.Write(rectArray[row_LB, iter] + ” “); noOfElementsTraversed++; } row_LB++; } } }