1. You are given a number n, representing the number of rows.
2. You are given a number m, representing the number of columns.Input Format
3. You are given n*m numbers, representing elements of 2d array a.
4. You are required to traverse and print the contents of the 2d array in form of a spiral.
Note - Please check the sample output for details.
A number nOutput Format
A number m
e11
e12..
e21
e22..
.. n * m number of elements
e11
e21
..
en1
en2
en3
..
enm
e(n-1)m
..
e1m
e1(m-1)
..
e12
e22
e32
..
Constraints
1 <= n <= 10^2
1 <= m <= 10^2
-10^9 <= e1, e2, .. n * m elements <= 10^9
Sample Input
3
5
11
12
13
14
15
21
22
23
24
25
31
32
33
34
35
Sample Output
11
21
31
32
33
34
35
25
15
14
13
12
22
23
24
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] A = new int[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
A[i][j] = sc.nextInt();
int minRow = 0, minCol = 0, maxRow = n-1, maxCol = m-1, totalEle = n*m,count = 0;
while(totalEle > count){
for(int i=minRow;i<=maxRow && count < totalEle;i++){
System.out.println(A[i][minCol]);
++count;
}
++minCol;
for(int i=minCol;i<=maxCol && count < totalEle;i++){
System.out.println(A[maxRow][i]);
++count;
}
--maxRow;
for(int i=maxRow;i>=minRow && count < totalEle;i--){
System.out.println(A[i][maxCol]);
++count;
}
--maxCol;
for(int i=maxCol;i>=minCol && count < totalEle;i--){
System.out.println(A[minRow][i]);
++count;
}
++minRow;
}
}
}
Comments
Post a Comment