Spiral Matrix I(II)

来源:互联网 发布:苹果手机mac怎么修改 编辑:程序博客网 时间:2024/05/22 04:34

题目一:螺旋序矩阵

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

 

思路

注意一些边界情况。

maxlevel = min(row,col)/2+min(row,col)%2;

这个也要注意。

 

class Solution {public:    vector<int> spiralOrder(vector<vector<int> > &matrix) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<int> result;        int row = matrix.size();        if(row<=0)             return result;        int col = matrix[0].size();        if(col==1){            for(int i=0;i<row;i++)                result.push_back(matrix[i][0]);            return result;                    }        int level = 0;        int maxlevel = min(row,col)/2+min(row,col)%2;        while(level<maxlevel)        {            for(int j=level;j<=col-1-level;j++){                result.push_back(matrix[level][j]);            }            for(int i=level+1;i<row-1-level;i++){                result.push_back(matrix[i][col-1-level]);            }                       if(row-1-level==level)                break;            for(int j=col-1-level;j>level;j--){                result.push_back(matrix[row-1-level][j]);            }            for(int i=row-1-level;i>level;i--){                result.push_back(matrix[i][level]);            }              level++;        }           return result;            }};

 

还可以用递归的方法。

题目二:Spiral Matrix II

class Solution {public:    vector<vector<int> > generateMatrix(int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function                vector<vector<int>> result(n,vector<int>(n,0));          if(n<=0)            return result;          int cur = 1;        int level = 0;          int maxlevel = n/2+n%2;          while(level<maxlevel)          {              for(int j=level;j<=n-1-level;j++){                  result[level][j] = cur++;              }              for(int i=level+1;i<n-1-level;i++){                  result[i][n-1-level] = cur++;              }                         if(n-1-level==level)                  break;              for(int j=n-1-level;j>level;j--){                  result[n-1-level][j] = cur++;              }              for(int i=n-1-level;i>level;i--){                  result[i][level] = cur++;              }                level++;          }             return result;              }  };  


 

 

 

 

原创粉丝点击