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

Spiral Matrix

时间:2014-11-20 21:42:11      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   sp   for   div   log   代码   bs   

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

只适合方阵的C++实现代码:

vector<int> spiralOrder(vector<vector<int> > &matrix)
    {
        if(matrix.empty()||matrix[0].empty())
            return vector<int>();
        vector<int> ret;
        int n=matrix.size();
        int count=n*n;
        int i=0;
        int j=0;
        while(count)
        {
            if(count==1)
            {
                ret.push_back(matrix[i][j]);
                break;
            }
            for(; j<n-i-1; j++)
            {
                ret.push_back(matrix[i][j]);
                count--;
            }
            for(; i<j; i++)
            {
                ret.push_back(matrix[i][j]);
                count--;
            }
            for(; j>n-i-1; j--)
            {
                ret.push_back(matrix[i][j]);
                count--;
            }
            for(; i>j; i--)
            {
                ret.push_back(matrix[i][j]);
                count--;
            }
            i++;
            j++;
        }
        return ret;
    }

 

Spiral Matrix

标签:style   blog   color   sp   for   div   log   代码   bs   

原文地址:http://www.cnblogs.com/wuchanming/p/4111548.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!