螺旋矩阵
解法一:数组遍历
import java.util.ArrayList;
import java.util.List;
public class LeetCode_054 {
public static List<Integer> spiralOrder(int[][] matrix) {
int row = matrix.length, column = matrix[0].length, count = row * column, x = 0, y = -1;
boolean[][] flag = new boolean[row][column];
List<Integer> result = new ArrayList<>();
while (count > 0) {
// 向右
while (y + 1 < column && !flag[x][y + 1]) {
y = y + 1;
result.add(matrix[x][y]);
flag[x][y] = true;
count--;
}
// 向下
while (x + 1 < row && !flag[x + 1][y]) {
x = x + 1;
result.add(matrix[x][y]);
flag[x][y] = true;
count--;
}
// 向左
while (y - 1 >= 0 && !flag[x][y - 1]) {
y = y - 1;
result.add(matrix[x][y]);
flag[x][y] = true;
count--;
}
// 向上
while (x - 1 >= 0 && !flag[x - 1][y]) {
x = x - 1;
result.add(matrix[x][y]);
flag[x][y] = true;
count--;
}
}
return result;
}
public static void main(String[] args) {
int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
for (Integer integer : spiralOrder(matrix)) {
System.out.print(integer + " ");
}
}
}