-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTriangleSnail.java
More file actions
68 lines (53 loc) · 1.43 KB
/
Copy pathTriangleSnail.java
File metadata and controls
68 lines (53 loc) · 1.43 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
package basic;
class TriangleSnail {
public int[] solution(int n) {
int[][] arr = new int[n][n];
int y = 0;
int x = 0;
int v = 1;
while(true) {
while (true) {
arr[y][x] = v++;
if ((y + 1) == n || arr[y + 1][x] != 0) {
break;
}
y++;
}
if ((x + 1) == n || arr[y][x + 1] != 0) break;
x++;
while (true) {
arr[y][x] = v++;
if ((x + 1) == n || arr[y][x + 1] != 0) break;
x++;
}
if (arr[y - 1][x - 1] != 0) break;
x--;
y--;
while (true) {
arr[y][x] = v++;
if(arr[y - 1][x - 1] != 0) break;
x--;
y--;
}
if ((y + 1) == n || arr[y + 1][x] != 0) break;
y++;
}
for (int[] ints : arr) {
for (int anInt : ints) {
System.out.print(anInt + " ");
}
}
System.out.println();
int[] answer = new int[v - 1];
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
answer[index++] = arr[i][j];
}
}
for (int i : answer) {
System.out.print(i + " ");
}
return answer;
}
}