import java.util.ArrayList; import java.util.List; /** * @author xnl * @Description: * @date: 2022/7/3 22:38 */ public class Solution { public static void main(String[] args) { Solution solution = new Solution(); int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; System.out.println(solution.spiralOrder(matrix).toString()); } public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); int m = matrix.length, n = matrix[0].length; int[][] directions = {{0 ,1}, {1, 0}, {0, -1}, {- 1, 0}}; boolean[][] vis = new boolean[m][n]; int direction = 0; int row = 0; int col = 0; for(int i = 0; i < m * n; i++ ){ res.add(matrix[row][col]); vis[row][col] = true; int next_row = row + directions[direction][0]; int next_col = col + directions[direction][1]; if (next_col < 0 || next_col >= n || next_row >= m || vis[next_row][next_col] ){ direction = (direction + 1) % 4; } row = row + directions[direction][0]; col = col + directions[direction][1]; } return res; } }