LeetCode 54. Spiral Matrix

题目:

给定一个m x n个元素的矩阵(m行,n列),按螺旋顺序返回矩阵的所有元素。

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],            Output: [1,2,3,6,9,8,7,4,5]
 [ 7, 8, 9 ]
]

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],          Output: [1,2,3,4,8,12,11,10,9,5,6,7]
  [9,10,11,12]
]

即,对于矩阵的每一层,从左上角开始,逆时针排列

 

方法:

类似【剑指offer第二版——面试题29(java)—— https://blog.csdn.net/qq_22527013/article/details/89641098

从矩阵最外层开始,往里每一层都逆时针遍历,加入到数组中,遍历分为四个部分:

1)在最上,从左往右遍历;2)在最右,从上往下

3)在最下,从右往左;4)最左,从下往上

需要注意边界的是否重复输入或遗漏输入,如下图中四个角的位置,容易出现重复或丢失,需要注意边界

 

代码:

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> re = new LinkedList<Integer>();
        if(matrix.length==0 || matrix[0].length==0) {
            return re;
        }
    	
        int i = 0;
        int n = (matrix.length>matrix[0].length)?matrix[0].length:matrix.length;
    	
        // 按层 由外向内
        while(i<n/2+n%2) {
            spiral(matrix, i, re);
            i++;
        }
        return re;
    }
    
    // 主要功能函数
    public void spiral(int[][] matrix, int times,List<Integer> re) {
        int m = matrix.length-1;
        int n = matrix[0].length-1;
    	
        // 本次矩阵边界
        int left = times;
        int right = n-times;
        int up = times;
        int down = m-times;
    	
        // 如果剩下的是1×1,直接添加
        if(left==right && up==down && left==up) {
            re.add(matrix[left][up]);
        }else {
            // 上:从左到右
            int loc = left;
            while(loc<=right) {
                re.add(matrix[up][loc++]);
            }
        	
            // 右:从上到下
            loc = up+1;
            while(loc<down) {
                re.add(matrix[loc++][right]);
            }
        	
            // 下:从右到左
            loc = right;
            while(loc>=left && up<down) {
                re.add(matrix[down][loc--]);
            }
        	
            // 左:从下到上
            loc = down-1;
            while(loc>up && left<right) {
                re.add(matrix[loc--][left]);
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值