题目:
Given a matrix of m ✕ 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 ]
]
You should return [1,2,3,6,9,8,7,4,5]
解答:
1 public class Solution { 2 public static void main(String[] args) { 3 int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; 4 List<Integer> elements = spiralOrder(matrix); 5 } 6 7 public List<Integer> spiralOrder(int[][] matrix) { 8 List<Integer> elements = new ArrayList<>(); 9 10 if(matrix.length == 0) { 11 return elements; 12 } 13 14 int m = matrix.length; 15 int n = matrix[0].length; 16 int row = 0; 17 int col = -1; 18 19 while(true) { 20 for(int i = 0; i < n; i++) { 21 elements.add(matrix[row][++col]); 22 } 23 24 if(--m == 0) { 25 break; 26 } 27 28 for(int i = 0; i < m; i++) { 29 elements.add(matrix[++row][col]); 30 } 31 32 if(--n == 0) { 33 break; 34 } 35 36 for(int i = 0; i < n; i++) { 37 elements.add(matrix[row][--col]); 38 } 39 40 if(--m == 0) { 41 break; 42 } 43 44 for(int i = 0; i < m; i++) { 45 elements.add(matrix[--row][col]); 46 } 47 48 if(--n == 0) { 49 break; 50 } 51 } 52 53 return elements; 54 } 55 }