-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralArray.java
More file actions
71 lines (68 loc) · 1.82 KB
/
SpiralArray.java
File metadata and controls
71 lines (68 loc) · 1.82 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
// not the cleanest solution but 100% faster than all java submissions
/**
* leetcode solutions comprises on using the left most coordinates and right most
* coordinates and using four loop to iterate in each direction and then incrementing
* and decrementing each corner value
*/
class Solution {
public List<Integer> spiralOrder(int[][] arr) {
int n = arr.length;
if(n == 0)
return (List)(new ArrayList<>());
int m = arr[0].length;
int max = n * m;
int r = m - 1;
int b = n - 1;
int l = 0;
int u = 1;
char dir = 'r';
int x = 0;
int y = 0;
int count = 0;
List<Integer> ans = new ArrayList<>();
while(count < max){
if(dir == 'r'){
if(x > r){
dir = 'b';
y++;
x--;
r--;
continue;
}
ans.add(arr[y][x++]);
}
if(dir == 'b'){
if(y > b){
dir = 'l';
y--;
x--;
b--;
continue;
}
ans.add(arr[y++][x]);
}
if(dir == 'l'){
if(x < l){
dir = 'u';
x++;
y--;
l++;
continue;
}
ans.add(arr[y][x--]);
}
if(dir == 'u'){
if(y < u){
dir = 'r';
y++;
x++;
u++;
continue;
}
ans.add(arr[y--][x]);
}
count++;
}
return ans;
}
}