-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspirally_traverse.java
More file actions
62 lines (51 loc) · 1.27 KB
/
spirally_traverse.java
File metadata and controls
62 lines (51 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* GeeksForGeeks - Spirally traversing the matrix
Link: https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix/0
Author: Shyam Kumar
Date: 14th March, 2019
*/
import java.util.Scanner;
class Spiral_traverse {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows, cols, i, j;
int t = sc.nextInt();
while(t > 0) {
rows = sc.nextInt();
cols = sc.nextInt();
int arr[][] = new int[rows][cols];
for( i = 0; i < rows; i++ ){
for( j = 0; j < cols; j++ ) {
arr[i][j] = sc.nextInt();
}
}
spirally_traverse( rows, cols, arr );
System.out.println();
t--;
}
}
static void spirally_traverse( int rows, int cols, int arr[][] ) {
int i, j, s;
s = 0;
while( (s < cols) && (s < rows) ) {
print_border( rows, cols, s, arr );
rows--;
cols--;
s++;
}
}
static void print_border( int rows, int cols, int s, int arr[][] ) {
int i, j;
for( i = s; i < cols; i++ )
System.out.print(arr[s][i]+" ");
for( j = s+1; j < rows; j++ )
System.out.print(arr[j][cols-1]+" ");
if( s != rows-1 ) {
for( i = cols-2; i >= s; i-- )
System.out.print(arr[rows-1][i]+" ");
}
if( s != cols-1 ) {
for( j = rows-2; j > s; j-- )
System.out.print(arr[j][s]+" ");
}
}
}