/**
* Print Matrix in spiral order
* @author PRATEEK
*/
class PrintSpiralMatrix {
/**
* Spiral order printing
* @param matrix
*/
public static void printSpiral(int[][] matrix)
{
int rowSize = matrix.length ;
int colSize = matrix[0].length;
int row=0,col=0,i,j,k;
while(row < rowSize && col < colSize)
{
i=col;
for(;i<colSize-col;i++)
System.
out.
print(matrix
[row
][i
]+" ");
i=row + 1;
for(;i<rowSize-row;i++)
System.
out.
print(matrix
[i
][colSize
-col
-1]+" ");
i=(colSize-1-col)-1;
for(;i>=col;i--)
System.
out.
print(matrix
[rowSize
-row
-1][i
]+" ");
i=(rowSize-1-row)-1;
for(;i>row;i--)
System.
out.
print(matrix
[i
][col
]+" ");
row++;
col++;
}
}
public static void main
(String[] args
) { int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20},
};
printSpiral(matrix);
}
}
LyoqCiAqIFByaW50IE1hdHJpeCBpbiBzcGlyYWwgb3JkZXIKICogQGF1dGhvciBQUkFURUVLCiAqLwoKY2xhc3MgUHJpbnRTcGlyYWxNYXRyaXggewoKCS8qKgoJICogU3BpcmFsIG9yZGVyIHByaW50aW5nCgkgKiBAcGFyYW0gbWF0cml4CgkgKi8KCXB1YmxpYyBzdGF0aWMgdm9pZCBwcmludFNwaXJhbChpbnRbXVtdIG1hdHJpeCkKCXsKCQlpbnQgcm93U2l6ZSA9IG1hdHJpeC5sZW5ndGggOwoJCWludCBjb2xTaXplID0gbWF0cml4WzBdLmxlbmd0aDsKCQkKCQlpbnQgcm93PTAsY29sPTAsaSxqLGs7CgkJCgkJd2hpbGUocm93IDwgcm93U2l6ZSAmJiBjb2wgPCBjb2xTaXplKQoJCXsKCQkJaT1jb2w7CgkJCWZvcig7aTxjb2xTaXplLWNvbDtpKyspCgkJCQlTeXN0ZW0ub3V0LnByaW50KG1hdHJpeFtyb3ddW2ldKyIgICIpOwoJCQkKCQkJCgkJCWk9cm93ICsgMTsKCQkJ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