Leetcode: Spiral Matrix. Java
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 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); int m = matrix.length; if(m == 0) return res; int n = matrix[0].length; //循环次数小于m/2和n/2 for(int i = 0; i < m/2 && i < n/2; i++){ for(int j = 0; j < n - 1 - i * 2; j++) res.add(matrix[i][i+j]); for(int j = 0; j < m - 1 - i * 2; j++) res.add(matrix[i+j][n-i-1]); for(int j = 0; j < n - 1 - i * 2; j++) res.add(matrix[m-i-1][n-i-1-j]); for(int j = 0; j < m - 1 - i * 2; j++) res.add(matrix[m-i-1-j][i]); } //循环结束后假设行数/列数是奇数,则还剩一行/列 if(m % 2 != 0 && m <= n){ for(int j = 0; j < n - (m/2) * 2; j++) res.add(matrix[m/2][m/2+j]); } else if(n % 2 != 0 && m > n){ for(int j = 0; j < m - (n/2) * 2; j++) res.add(matrix[n/2+j][n/2]); } return res; } }