码迷,mamicode.com
首页 > 其他好文 > 详细

Spiral Matrix

时间:2016-02-29 00:21:04      阅读:162      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!