Matrix相关
Spiral Matrix
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
int rowStart = 0, rowEnd = matrix.length - 1, colStart = 0, colEnd = matrix[0].length - 1;
int dir = 0;
while (rowStart <= rowEnd && colStart <= colEnd) {
switch(dir) {
case 0: //right
for (int j = colStart; j <= colEnd; j++) {
res.add(matrix[rowStart][j]);
}
rowStart++;
break;
case 1: //down
for (int i = rowStart; i <= rowEnd; i++) {
res.add(matrix[i][colEnd]);
}
colEnd--;
break;
case 2: //left
for (int j = colEnd; j>= colStart; j--) {
res.add(matrix[rowEnd][j]);
}
rowEnd--;
break;
case 3: //up
for (int i = rowEnd; i >= rowStart; i--) {
res.add(matrix[i][colStart]);
}
colStart++;
break;
}
dir = (dir + 1) % 4;
}
return res;
}Spiral Matrix II
Last updated