螺旋矩阵

题目:螺旋矩阵
分类:数组、矩阵、模拟
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

路径范围
往右走最大值right
往左走最小值left
往下走最大值bottom
往上走最小值top
【细节】right是的最大值,bottom是的最大值

思路

  • 起点——向右——到right,right不变,top+1(往下走一行)——向下——到bottom,bottom不变,right-1(向左走一列)——向左——到left,left不变,bottom-1(向上走一行)——向上——到top,top不变,left+1(向右走一行,此时已在第二排第二列了)完成一周

  • 继续螺旋循环,直到left>right,top<bottom退出,实则在二者相等时:仅剩一个元素,循环这一遍之后结束

【细节】

  1. 矩阵为空的处理
  2. 每次走都有两个条件,eg:即使top现在不变,也要保证top<=bottom的前提,否则会越界
  3. java中用.length获取大小,c++中用.size()
/*java*/
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> output = new ArrayList<>();
    //std::vector<int> spiralOrder(std::vector<std::vector<int>>& matrix) {
    //std::vector<int> output;
    if(matrix==null||matrix.length==0||matrix[0].length==0)
        return output;

        int left=0;
        int top=0;
        int bottom=matrix.length-1;
        int right=matrix[0].length-1;

        int i=0;
        while(left<=right && top<=bottom){
            for(i=left;i<=right&&top<=bottom;++i){
                output.add(matrix[top][i]);
            }
            top++;
            for(i=top;i<=bottom&&left<=right;++i){
                output.add(matrix[i][right]);
            }
            right--;
            for(i=right;i>=left&&top<=bottom;--i){
                output.add(matrix[bottom][i]);
            }
            bottom--;
            for(i=bottom;i>=top&&left<=right;--i){
                output.add(matrix[i][left]);
            }
            left++;
        }
        return output;
    }
};
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值