-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
53 lines (42 loc) · 1.4 KB
/
SpiralMatrix.java
File metadata and controls
53 lines (42 loc) · 1.4 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
package swe.Array;
import java.util.*;
public class SpiralMatrix {
public static List<Integer> spiralSequence(int[][] matrix) {
List<Integer> output = new ArrayList<>();
int leftColum = 0;
int rightColum = matrix.length - 1;
int topRow = 0;
int bottomRow = matrix[0].length - 1;
while (leftColum <= rightColum && topRow <= bottomRow) {
for (int i = leftColum; i <= rightColum; i++) {
output.add(matrix[topRow][i]);
}
topRow++;
for (int i = topRow; i <= bottomRow; i++) {
output.add(matrix[i][rightColum]);
}
rightColum--;
if (topRow <= bottomRow) {
for (int i = rightColum; i >= leftColum; i--) {
output.add(matrix[bottomRow][i]);
}
}
bottomRow--;
if (leftColum <= rightColum) {
for (int i = bottomRow; i >= topRow; i--) {
output.add(matrix[i][leftColum]);
}
}
leftColum++;
}
return output;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(spiralSequence(matrix));
}
}