Interview Questions

Print an mxn matrix spirally. Write code for the same.

Microsoft Interview Questions and Answers


(Continued from previous question...)

78. Print an mxn matrix spirally. Write code for the same.

Question:
Print an mxn matrix spirally. Write code for the same.


maybe an answer:


class SpiralMatrix {

public static int re=0;
public static int rs=0;
public static int ce=0;
public static int cs=0;
int[][] a;

public void spiralMatrix(int[][] a)
{
this.a=a;
while(rs<=re && cs<=ce)
{
printTop();
printRight();
printBottom();
printLeft();
}
}

private void printLeft()
{
if(rs<=re && cs<=ce)
{
for(int i=re;i>=rs;i--)
System.out.print(a[i][cs]+" ");
cs++;
}

}

private void printBottom()
{
if(rs<=re && cs<=ce)
{
for(int i=ce;i>=cs;i--)
System.out.print(a[re][i]+" ");
re--;
}
}

private void printRight()
{
if(rs<=re && cs<=ce)
{
for(int i=rs;i<<=re;i++)
System.out.print(a[i][ce]+" ");
ce--;
}
}

private void printTop()
{
if(rs<=re && cs<=ce)
{
for(int i=cs;i<=ce;i++)
System.out.print(a[rs][i]+" ");
rs++;
}
}

public static void main(String[] args)
{
int[][] a={{1},{4},{7}};
SpiralMatrix spiralMatrix=new SpiralMatrix();
SpiralMatrix.rs=0;
SpiralMatrix.cs=0;
SpiralMatrix.re=a.length-1;
SpiralMatrix.ce=a[0].length-1;
spiralMatrix.spiralMatrix(a);
}
}

(Continued on next question...)

Other Interview Questions