Thursday, December 20, 2018
54. Spiral Matrix
Version #2 Two Pointers[TODO]
Two Pointers on [rowStart, rowEnd] [colStart, colEnd]
Version #1 Recursion
Using an index to mark the layer
Even it is not a square matrix, we can still use [index, index] to mark the left top boundary
100.00 %
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return result;
helper(matrix, 0, matrix.length, matrix[0].length, result);
return result;
}
private void helper(int[][] matrix, int index, int rows, int cols, List<Integer> result) {
if (rows <= 0 || cols <= 0) return;
// System.out.println(index);
int y = index;
int x = index;
y = index;
for (x = index; x < index + cols; x++) {
result.add(matrix[y][x]);
}
x--;
for (y = y + 1; y < index + rows; y++) {
result.add(matrix[y][x]);
}
if (rows > 1 && cols > 1) {
y--;
for (x = x - 1; x >= index && y > index; x--) {
result.add(matrix[y][x]);
}
x++;
for (y = y - 1; y > index; y--) {
result.add(matrix[y][x]);
}
}
helper(matrix, index + 1, rows - 2, cols - 2, result);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment