首页 > 其他 > 详细

Spiral Matrix

时间:2016-02-29 00:20:48      阅读:197      评论:0      收藏:0      [点我收藏+]

题目:

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

cpp:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        if (matrix.empty())
            return result;
        int m = matrix.size();
        int n = matrix[0].size();
        result.reserve(m * n);

        int r = 0;
        int c = 0;

        int i;
        while (r < m / 2 && c < n / 2) {
            //left to right
            for (i = c; i < n - c; i++) {
                result.push_back(matrix[r][i]);
            }
            //up to down
            for (i = r + 1; i < m - r; i++) {
                result.push_back(matrix[i][n - c - 1]);
            }
            //right to left
            for (i = n - c - 2; i >= c; i--) {
                result.push_back(matrix[m - c - 1][i]);
            }
            //down to up
            for (i = m - r - 2; i > r; i--) {
                result.push_back(matrix[i][r]);
            }
            r++;
            c++;
        }

        if (m >= n && 2*c < n) {
            for (i = r; i < m - r; i++) {
                result.push_back(matrix[i][c]);
            }
        }
        if(m<n && 2*r < m){
            for (i = c; i < n - c; i++) {
                result.push_back(matrix[r][i]);
            }
        }
        return result;
    }
};

 

Spiral Matrix

原文:http://www.cnblogs.com/wxquare/p/5225865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!