螺旋矩阵(Java)

螺旋矩阵

(牛客网—牛客题霸算法篇—NC38)

题目描述

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

思路

Java实现
这道题目属于一道模拟题,只需要找出输出的规则和边界终止条件即可。

按时钟指针转动规则:
我们可以按照时钟中指针的转动方向来模拟这道题目的输出结果。
我们从最上面开始遍历,接着到边的时候就向下遍历,然后向左向上遍历,当一圈遍历结束的时候则进入里圈进行遍历。

代码实现

import java.util.*;

public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> res = new ArrayList<>();
        if(matrix.length == 0)
            return res;
        // 定义四个指针,并且充当边界限制的作用
        int top = 0, bottom = matrix.length-1;
        int left = 0, right = matrix[0].length-1;
 
        while( top < (matrix.length+1)/2 && left < (matrix[0].length+1)/2 ){
            //上面  左到右
            for(int i = left; i <= right; i++){
                res.add(matrix[top][i]);
            }
            //右边 上到下
            for(int i = top+1; i <= bottom; i++){
                res.add(matrix[i][right]);
            }
            //下面  右到左
            for(int i = right-1; top!=bottom && i>=left; i--){
                res.add(matrix[bottom][i]);
            }
            //左边 下到上
            for(int i = bottom-1; left!=right && i>=top+1; i--){
                res.add(matrix[i][left]);
            }
            // 遍历完一圈之后,所有往里面靠
            ++top;
            --bottom;
            ++left;
            --right;
        }
        return res;
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值