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


思路:这是个m,n矩阵,每次绕着外围扫一圈,扫到剩下的最后一个 [ x ], [x, y, z], [ x ], [ y ]

那么定义宽和高,可得到四个角。扫完第一行,heightStart+1,扫完最右边一列,widthEnd-1。

由于heightStart加了一,check是否已经是最底下一行。 



var spiralOrder = function(matrix) {
    var result = [];
    var n = matrix.length;
    var m = (matrix.length===0? 0:matrix[0].length);
    var widthStart = 0,
        widthEnd = m-1,
        heightStart = 0,
        heightEnd = n-1;
    while (widthStart<=widthEnd&&heightStart<=heightEnd) {
        for (var i=widthStart;i<=widthEnd;i++) {
            result.push(matrix[heightStart][i]);
        }
        heightStart++
        for (var j=heightStart;j<=heightEnd;j++) {
            result.push(matrix[j][widthEnd]);
        }
        widthEnd--
        if (heightStart<=heightEnd) {
            for (var k=widthEnd;k>=widthStart;k--) {
               result.push(matrix[heightEnd][k]);
            }      
            heightEnd--
        }
        if (widthStart<=widthEnd) {
            for (var x=heightEnd;x>=heightStart;x--) {
                result.push(matrix[x][widthStart])
            }
            widthStart++
        }
    }
        return result;
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值