首页 > 代码库 > Leetcode: Spiral Matrix

Leetcode: Spiral Matrix

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].

难度:87,这道题跟 Rotate Image 很相似,都是需要把矩阵分割成层来处理,每一层都是按:1. 正上方;2. 正右方;3. 正下方;4. 正左方这种顺序添加元素到结果集合。实现中要注意两个细节,一个是因为题目中没有说明矩阵是不是方阵,因此要先判断一下行数和列数来确定螺旋的层数,mina(行, 列) /2才是螺旋数。二是有可能存在这种情况比如:3*4矩阵,螺旋只有一层,但中间还有一行元素没有没加入。所以最后要将剩余的走完。

 1 public class Solution { 2     public List<Integer> spiralOrder(int[][] matrix) { 3         ArrayList<Integer> res = new ArrayList<Integer>(); 4         if (matrix==null || matrix.length==0 || matrix[0].length==0) return res; 5         int Min = Math.min(matrix.length, matrix[0].length); 6         int levelMax = Min / 2; 7         for (int level=0; level<levelMax; level++) { 8             for (int i=level; i<matrix[0].length-1-level; i++) { 9                 res.add(matrix[level][i]);10             }11             for (int i=level; i<matrix.length-1-level; i++) {12                 res.add(matrix[i][matrix[0].length-1-level]);13             }14             for (int i=matrix[0].length-1-level; i>level; i--) {15                 res.add(matrix[matrix.length-1-level][i]);16             }17             for (int i=matrix.length-1-level; i>level; i--) {18                 res.add(matrix[i][level]);19             }20         }21         if (Min % 2 == 1) {22             if (matrix.length < matrix[0].length) {23                 for (int i=levelMax; i<matrix[0].length-levelMax; i++) {24                     res.add(matrix[levelMax][i]);25                 }26             }27             else {28                 for (int i=levelMax; i<matrix.length-levelMax; i++) {29                     res.add(matrix[i][levelMax]);30                 }31             }32         }33         return res;34     }35 }

 

Leetcode: Spiral Matrix