Print a matrix in Spiral Form without using extra space and n² time complexity
public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> output = new ArrayList();
int rowMax = matrix.length-1;
int colMax = matrix[0].length-1;
int listSize = (rowMax+1)*(colMax+1);
int rowMin = 0;
int colMin = 0;
int rowIndex =0;
int colIndex =0;
while(rowMin<=rowMax && colMin<=colMax && output.size()<listSize){
for(int i=colMin; i<=colMax; i++){
output.add(matrix[rowIndex][colIndex]);
colIndex++;
}
if(rowMin == rowMax){
break;
}
rowMin++;
rowIndex++;
if(colIndex>colMax)
colIndex — ;
for(int i=rowMin; i<=rowMax; i++){
output.add(matrix[rowIndex][colIndex]);
rowIndex++;
}
if(colMin == colMax){
break;
}
colMax — ;
colIndex — ;
if(rowIndex>rowMax)
rowIndex — ;
for(int i=colMax; i>=colMin; i — ){
output.add(matrix[rowIndex][colIndex]);
colIndex — ;
}
rowMax — ;
rowIndex — ;
if(colIndex<colMin)
colIndex++;
for(int i=rowMax; i>=rowMin; i — ){
output.add(matrix[rowIndex][colIndex]);
rowIndex — ;
}
colMin++;
colIndex++;
if(rowIndex < rowMin)
rowIndex++;
}
return output;
}