-
Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathSpiral_Matrix.java
108 lines (107 loc) · 3.13 KB
/
Spiral_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
class Spiral_Matrix {
public static void main(String[] args){
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
Spiral_Matrix ob = new Spiral_Matrix();
System.out.println(ob.spiralOrder(matrix));
}
public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> ans = new ArrayList<>();
boolean[][] visited = new boolean[matrix.length][matrix[0].length];
int count = 0;
int row = 0;
int col = 0;
boolean right = true;
boolean left = false;
boolean down = false;
boolean up = false;
boolean curr = right;
while(count!=(matrix.length*matrix[0].length)){
if(!valid(row,col,matrix)){
if(curr==right){
col--;
row++;
down = true;
right = false;
curr = down;
}
else if(curr==left){
col++;
row--;
left = false;
up = true;
curr = up;
}
else if(curr==down){
col--;
row--;
down = false;
left = true;
curr = left;
}
else if(curr==up){
col++;
row--;
up = false;
right = true;
curr = right;
}
}
if(!visited(row,col,visited)){
visited[row][col] = true;
ans.add(matrix[row][col]);
count++;
if(right){
col++;
}
else if(left){
col--;
}
else if(down){
row++;
}
else if(up){
row--;
}
}
else{
if(curr==right){
col--;
row++;
down = true;
right = false;
curr = down;
}
else if(curr==left){
col++;
row--;
left = false;
up = true;
curr = up;
}
else if(curr==down){
col--;
row--;
down = false;
left = true;
curr = left;
}
else if(curr==up){
col++;
row++;
up = false;
right = true;
curr = right;
}
}
}
return ans;
}
private boolean valid(int r, int c, int[][] matrix){
boolean row = (r>=0)&&(r<matrix.length);
boolean col = (c>=0)&&(c<matrix[0].length);
return row&&col;
}
private boolean visited(int r, int c, boolean[][] mat){
return mat[r][c];
}
}