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

Spiral Matrix I II

时间:2014-12-19 00:28:58      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   io   color   sp   for   strong   on   

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

题解:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> res;
        int row = matrix.size();
        if(row==0)
            return res;
        int col = matrix[0].size();
        int k = (1+min(row, col))/2;
        int row0 = 0, col0 = 0;
        int i=0, j=0;
        while(k--) {
            if((row-row0)==1)
                for(j=col0;j<col;j++)
                    res.push_back(matrix[row0][j]);
            else if((col-col0)==1)
                for(i=row0;i<row;i++)
                    res.push_back(matrix[i][col-1]);
            else {
                for(j=col0;j<col;j++)
                     res.push_back(matrix[row0][j]);
                res.pop_back();
                for(i=row0;i<row;i++)
                     res.push_back(matrix[i][col-1]);
                res.pop_back();
                for(j=col-1;j>=col0;j--)
                     res.push_back(matrix[row-1][j]);
                res.pop_back();
                for(i=row-1;i>=row0;i--)
                     res.push_back(matrix[i][col0]);
                res.pop_back();
                row0++;col0++;
                row--;col--;
            }
        }
        return res;
    }
};

 

Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
题解:
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > res(n, vector<int>(n));
        int start = 0;
        int end = n-1;
        int i=0, j=0;
        int num = 1;
        while(start<end) {
            for(j=start;j<end;j++)
                res[start][j] = num++;
            for(i=start;i<end;i++)
                res[i][end] = num++;
            for(j=end;j>start;j--)
                res[end][j] = num++;
            for(i=end;i>start;i--)
                res[i][start] = num++;
            start++;end--;
        }
        if(start==end)
            res[end][end] = num;
        return res;
    }
};

 

Spiral Matrix I II

标签:style   blog   ar   io   color   sp   for   strong   on   

原文地址:http://www.cnblogs.com/jiasaidongqi/p/4172854.html

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