Leetcode54. Spiral Matrix解题方案

Leetcode54. Spiral Matrix

题目描述

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

思路

有四个方向right, left, top, bottom.

  1. direction=“right”, 当到达最右边界时,代表本行输出结束,top++,
  2. direction=“bottom”,当到达最下边界时, right–,
  3. direction = “left”,当到达最左边界是 bottom–,
  4. direction=“top”,当到达top时候,left++,direction=“right”.

代码

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
         //result
        List<Integer> result = new ArrayList&lt;&gt;();
        if (matrix.length == 0) return result;
        //获取行数---Y行
        int lenY =matrix.length;
        //获取列数---X列
        int lenX = matrix[0].length;
        String direction = &quot;right&quot;;
        int left=0;
        int right = lenX-1;
        int down =0;
        int up = lenY-1;
        while(left&lt;=right &amp;&amp; down&lt;=up){
            if(direction == &quot;right&quot;){
                for(int i=left;i&lt;=right;i++){
                    result.add(matrix[down][i]);
                }
                down++;
                direction = &quot;down&quot;;
            }else if(direction==&quot;down&quot;){
                for(int i=down;i&lt;=up;i++){
                    result.add(matrix[i][right]);
                }
                right--;
                direction = &quot;left&quot;;
            }else if(direction==&quot;left&quot;){
                for(int i=right;i&gt;=left;i--){
                    result.add(matrix[up][i]);
                }
                up--;
                direction =&quot;up&quot;;
            }else if(direction==&quot;up&quot;){
                for(int i=up;i&gt;=down;i--){
                    result.add(matrix[i][left]);
                }
                left++;
                direction = &quot;right&quot;;
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值