Spiral Matrix
- Get link
- X
- Other Apps
For a given two-dimensional integer array/list of size (N x M), print it in a spiral form. That is, you need to print in the order followed for every iteration:
a. First row(left to right)
b. Last column(top to bottom)
c. Last row(right to left)
d. First column(bottom to top)
Sample Input 1:
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sample Output 1:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
import java.util.Scanner;
public class SpiralMatrix {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int input[][] = new int[n][m];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
input[i][j] = s.nextInt();
}
}
spiralPrint(input);
}
public static void spiralPrint(int matrix[][]){
int rs= 0;
int cs= 0;
int re= matrix.length-1;
int ce= matrix[0].length-1;
int total = matrix.length * matrix.length;
int c= 0;
while(c<total)
{
for(int i=cs;i<=ce;i++)
{
System.out.print(matrix[rs][i]+ " ");
c++;
}
rs++;
for(int i=rs;i<=re;i++)
{
System.out.print(matrix[i][ce]+ " ");
c++;
}
ce--;
for(int i=ce;i>=cs;i--)
{
System.out.print(matrix[re][i]+ " ");
c++;
}
re--;
for(int i=re;i>=rs;i--)
{
System.out.print(matrix[i][cs]+ " ");
c++;
}
cs++;
}
}
}
- Get link
- X
- Other Apps
Comments
Post a Comment