Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
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 { /** * @param matrix a matrix of m x n elements * @return an integer list */ public List<Integer> spiralOrder(int[][] matrix) { // Write your code here List<Integer> res = new ArrayList<Integer>(); if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res; int m = matrix.length; int n = matrix[0].length; int layer = 0; while((layer < m - layer - 1) && (layer < n - 1 - layer)){ for(int i = 0; i < n - layer - 1 - layer; i++) res.add(matrix[layer][layer + i]); for(int i = 0; i < m - layer - 1 - layer; i++) res.add(matrix[layer + i][n - layer - 1]); for(int i = 0; i < n - layer - 1 - layer; i++) res.add(matrix[m - layer - 1][n - layer - 1 - i]); for(int i = 0; i < m - layer - 1 - layer; i++) res.add(matrix[m - layer - 1 - i][layer]); layer++; } if(m > n){ if(layer == n - 1 - layer){ for(int i = layer; i <= m - layer - 1; i++) res.add(matrix[i][layer]); } } else if(m < n){ if(layer == m - 1 - layer){ for(int i = layer; i <= n - layer - 1; i++) res.add(matrix[layer][i]); } } else{ if(layer == m - 1 - layer){ res.add(matrix[layer][layer]); } } return res; } }
时间: 2024-10-13 06:51:33