forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral traversal in matrix.java
111 lines (68 loc) · 1.87 KB
/
Spiral traversal in matrix.java
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/{ Driver Code Starts
import java.io.*;
import java.util.*;
class GFG
{
public static void main(String args[])throws IOException
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int r = sc.nextInt();
int c = sc.nextInt();
int matrix[][] = new int[r][c];
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
matrix[i][j] = sc.nextInt();
}
Solution ob = new Solution();
ArrayList<Integer> ans = ob.spirallyTraverse(matrix, r, c);
for (Integer val: ans)
System.out.print(val+" ");
System.out.println();
}
}
}
// } Driver Code Ends
class Solution
{
static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c)
{
ArrayList<Integer> res=new ArrayList<>();
int top=0;
int down=r-1;
int right=c-1;
int left=0;
int dir=0;
while(top<=down&&left<=right){
if(dir==0){
for(int i=left;i<=right;i++){
res.add(matrix[top][i]);
}
top+=1;
}
else if(dir==1){
for(int i=top;i<=down;i++){
res.add(matrix[i][right]);
}
right-=1;
}
else if(dir==2){
for(int i=right;i>=left;i--){
res.add(matrix[down][i]);
}
down-=1;
}
else if(dir==3){
for(int i=down;i>=top;i--){
res.add(matrix[i][left]);
}
left+=1;
}
dir=(dir+1)%4;
}
return res;
}
}