#374 Spiral Matrix

本文介绍了一种将矩阵元素按螺旋顺序遍历的方法,并提供了一个通过边界控制实现螺旋遍历的具体算法实例。该算法适用于m x n大小的矩阵。

题目描述:

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

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

题目思路:

这题和#381一样,只要设好了boundary,再注意下while loop break的条件,再仔细些就不会有问题。

Mycode(AC = 27ms):

class Solution {
public:
    /**
     * @param matrix a matrix of m x n elements
     * @return an integer array
     */
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        // Write your code here
        vector<int> ans;
        
        int num_rows = matrix.size();
        if (num_rows == 0) return ans;
        
        ans.resize(num_rows * matrix[0].size());
        
        int upper_row = 0,
            down_row = num_rows - 1,
            left_col = 0,
            right_col = matrix[0].size() - 1,
            count = 0;
            
        while (count < ans.size()) {
            // get upper row
            for (int i = left_col; i <= right_col; i++) {
                ans[count++] = matrix[upper_row][i];
            }
            upper_row++;
            
            if (count >= ans.size()) break;
            
            // get right col
            for (int i = upper_row; i <= down_row; i++) {
                ans[count++] = matrix[i][right_col];
            }
            right_col--;
            
            if (count >= ans.size()) break;
            
            // get bottom row
            for (int i = right_col; i >= left_col; i--) {
                ans[count++] = matrix[down_row][i];
            }
            down_row--;
            
            if (count >= ans.size()) break;
            
            // get left col
            for (int i = down_row; i >= upper_row; i--) {
                ans[count++] = matrix[i][left_col];
            }
            left_col++;
        }
        
        return ans;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值