Java Implementation LeetCode (54. Helical Matrix)
- 2021-10-15 10:34:11
- OfStack
LeetCode54. Implementation of Helical Matrix java
Title
Medium difficulty Given a matrix with m x n elements (m row, n column), return all the elements in the matrix in a clockwise spiral order.Example 1:
Enter:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Example 2:
Enter:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Outputs: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Train of thought
Find out the coordinates of each point, each point goes one position in four directions, namely, right, down, left and up, maintains one direction variable, and makes corresponding boundary judgment in different directions. Every time you encounter a boundary, you must change the direction and shorten the original boundary size.
Solution
public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> order = new ArrayList<>();
if (matrix.length == 0 || matrix[0].length == 0) {
return order;
}
int m = matrix.length;
int n = matrix[0].length;
int len = m * n;
int row = 0;
int col = 0;
int leftMin = 0;
// Every time you go up and down, left and right 4 Four directions, 1 Go only once 1 Lattice
// Be careful, because it is from ( 1,1 ), so the upper bound is the smallest row Is the first 2 Row 1
int topMin = 1;
// Initial direction value
int k = 0;
int[][] dir = {
{1, 0, -1, 0},
{0, 1, 0, -1}
};
for (int i = 0; i < len; i++) {
order.add(matrix[row][col]);
col += dir[0][k % 4];
row += dir[1][k % 4];
switch (k % 4) {
case 0:
// Right
if (col > n - 1) {
col = n - 1;
row++;
k++;
n--;
}
break;
case 1:
// Under
if (row > m - 1) {
row = m - 1;
col--;
k++;
m--;
}
break;
case 2:
// Left
if (col < leftMin) {
col = leftMin;
leftMin++;
row--;
k++;
}
break;
case 3:
// Upper
if (row < topMin) {
row = topMin;
topMin++;
col++;
k++;
}
break;
}
}
return order;
}
Results
2ms defeated 99.74%