Print given matrix in spiral form
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
When we look at array indices,
i) At top we have row as constant and column varying from left to right.
ii) At right we have column as constant and row varying from top to bottom.
iii) At bottom we have row as constant and column varying from right to left.
iv) At left we have column as constant and row varying from bottom to top.
Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[][] a ={{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18}};
int m = a.length;
int n = a[0].length;
int top = 0, bottom = m-1, left = 0, right = n-1;
while(top<=bottom && left<=right){
//Print top row
for(int i=left; i<=right; i++){
System.out.print(a[top][i]+" ");
}
top++;
//Print right column
for(int i=top; i<=bottom; i++){
System.out.print(a[i][right]+" ");
}
right--;
//print last row
if(top <= bottom){
for(int i=right; i>=left; i--){
System.out.print(a[bottom][i]+" ");
}
bottom--;
}
//print left column
if(left <= right ){
for(int i=bottom; i>=top; i--){
System.out.print(a[i][left]+" ");
}
left++;
}
}
}
}
Output:
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
Comments
Post a Comment