public class DayCode { public static void main(String[] args) { int[][] matrix = new int[][]{{1, 2}, {3, 4}}; List<Integer> ans = new DayCode().spiralOrder(matrix); System.out.println(ans.toString()); }
/** * 时间复杂度O(rows * cols) * 空间复杂度O(rows * cols) * https://leetcode-cn.com/problems/spiral-matrix/ * * @param matrix * @return */ public List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return ans; }
int rows = matrix.length; int cols = matrix[0].length; int total = rows * cols; boolean[][] visited = new boolean[rows][cols]; int row = 0; int col = 0; int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int directionIdx = 0; for (int i = 0; i < total; i++) { ans.add(matrix[row][col]); visited[row][col] = true; int nextRow = row + directions[directionIdx][0]; int nextCol = col + directions[directionIdx][1]; if (nextRow < 0 || nextRow >= rows || nextCol < 0 || nextCol >= cols || visited[nextRow][nextCol]) { directionIdx = (directionIdx + 1) % 4; } row += directions[directionIdx][0]; col += directions[directionIdx][1]; } return ans; }}
评论