SpiralTraversalOfMatrix


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 List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList();

int rowStart = 0, rowEnd = matrix.length - 1, colStart = 0, colEnd = matrix[0].length - 1;

while (rowStart <= rowEnd && colStart <= colEnd) {
for(int i = colStart; i <= colEnd; i++) {
res.add(matrix[rowStart][i]);
}
rowStart++;

if (rowStart > rowEnd) {
break;
}
for (int i = rowStart; i <= rowEnd; i++) {
res.add(matrix[i][colEnd]);
}
colEnd--;

if (colStart > colEnd) { 
break;
}
for (int i = colEnd; i >= colStart; i--) {
res.add(matrix[rowEnd][i]);
}
rowEnd--;

for (int i = rowEnd; i >= rowStart; i-- ) {
res.add(matrix[i][colStart]);
}
colStart++;
}
return res;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s