-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathPrintSpiral.java
More file actions
71 lines (63 loc) · 1.76 KB
/
Copy pathPrintSpiral.java
File metadata and controls
71 lines (63 loc) · 1.76 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
63
64
65
66
67
68
69
70
71
import java.util.Scanner;
public class PrintSpiral {
public static int[][] input() {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c[][] = new int[a][b];
for (int x = 0; x < a; x++) {
for (int y = 0; y < b; y++) {
c[x][y] = sc.nextInt();
}
}
return c;
}
public static void printSpiral1(int a[][] )
{
int top=0, down=a.length-1, left=0, right=a[0].length-1, dir=0;
while(top<=down && left <= right)
{
if(dir==0)
{
for(int i=left; i<=right; i++)
{
System.out.print(a[top][i]+" ");
}
top++;
}
else if(dir==1)
{
for(int i=top; i<=down; i++)
{
System.out.print(a[i][right]+" ");
}
right--;
}
else if(dir==2)
{
for(int i=right; i>=left ; i--)
{
System.out.print(a[down][i]+" ");
}
down--;
}
else if(dir==3)
{
for(int i=down; i>=top ; i--)
{
System.out.print(a[i][left]+" ");
}
left++;
}
dir =(dir+1)%4;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int x = 1; x <= t; x++) {
int a[][] = input();
printSpiral1(a);
}
}
}