Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
1 public class Solution { 2 public List<Integer> spiralOrder(int[][] matrix) { 3 List<Integer> result = new ArrayList<>(); 4 if (matrix == null || matrix.length == 0) { 5 return result; 6 } 7 int m = matrix.length; 8 int n = matrix[0].length; 9 if (m == 1) { 10 for (int i = 0; i < n; i++) { 11 result.add(matrix[0][i]); 12 } 13 return result; 14 } 15 if (n == 1) { 16 for (int i = 0; i < m; i++) { 17 result.add(matrix[i][0]); 18 } 19 return result; 20 } 21 int xStart = 0; 22 int yStart = 0; 23 while (n > 0 && m > 0) { 24 if (m == 1 && n == 1) { 25 result.add(matrix[yStart][xStart]); 26 return result; 27 } 28 if (m == 1 && n > 1) { 29 for (int i = 0; i < n; i++) { 30 result.add(matrix[yStart][xStart + i]); 31 } 32 return result; 33 } 34 if (n == 1 && m > 1) { 35 for (int i = 0; i < m; i++) { 36 result.add(matrix[yStart + i][xStart]); 37 } 38 return result; 39 } 40 for (int i = 0; i < n - 1; i++) { 41 result.add(matrix[yStart][xStart + i]); 42 } 43 for (int i = 0; i < m - 1; i++) { 44 result.add(matrix[yStart + i][xStart + n - 1]); 45 } 46 for (int i = 0; i < n - 1; i++) { 47 result.add(matrix[yStart + m - 1][xStart + n - 1 - i]); 48 } 49 for (int i = 0; i < m - 1; i++) { 50 result.add(matrix[yStart + m - 1 - i][xStart]); 51 } 52 ++xStart; 53 ++yStart; 54 n = n - 2; 55 m = m - 2; 56 } 57 return result; 58 } 59 }
时间: 2024-08-09 02:18:15