I am trying to print a mxn size matrix in a spiral manner. I tried to work this code through Java and I was able to print the spiral correctly if rows = columns. For unequal rows and columns I tend to have repetitions in printing. So it prints all the way to the center correctly but then it repeats one or more elements. I tried debugging but could not reach far. Can anyone help me with this? Here is the code I have got so far.
public class SpiralMatrix {
public static void main (String args[]){
int[][] mat = { {1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11,12, 13, 14, 15}};
int i,n=3,m=5,r=m-1,q=n-1;
while(q>0 && r>0){
for(i=m-1-r;i<=r;i++){
System.out.println(mat[m-1-r][i]);
}
for(i=n-1-q+1;i<=q;i++){
System.out.println(mat[i][r]);
}
for(i=r-1;i>=m-1-r;i--){
System.out.println(mat[q][i]);
}
for(i=q-1;i>=n-1-q+1;i--){
System.out.println(mat[i][n-1-q]);
}
q--;
r--;
}
}
}
The output of this is as follows:
1
2
3
4
5
10
15
14
13
12
11
6
7
8
9
8
7
So after reaching the middle value 9 it tracks back to 8 and 7. PS: This is not a homework, I am brushing up my skills for interviews. And please go easy on me, I am a life long learner! Thanks! I will appreciate your help.