leetcode之Spiral Matrix

转自:http://blog.csdn.net/martin_liang/article/details/8982562

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]  view plain copy
  1. class Solution {  
  2.   
  3.     int min(int a, int b)  
  4.     {  
  5.         if (a > b)  
  6.             return b;  
  7.         return a;  
  8.     }  
  9. public:  
  10.     vector<int> spiralOrder(vector<vector<int> > &matrix) {  
  11.         // Start typing your C/C++ solution below  
  12.         // DO NOT write int main() function  
  13.           
  14.         vector<int> retVector;  
  15.           
  16.         if (matrix.size() == 0)  
  17.             return retVector;  
  18.               
  19.         int rows = matrix.size();  
  20.         int cols = matrix[0].size();  
  21.         int maxLoop = min(rows, cols);  
  22.           
  23.           
  24.         for (int loop = 0; loop < maxLoop/2; loop++)  
  25.         {  
  26.             for (int i = loop; i<cols-loop; i++)  
  27.                 retVector.push_back(matrix[loop][i]);  
  28.               
  29.             for (int j = loop+1; j<rows-loop; j++)  
  30.                 retVector.push_back(matrix[j][cols-1-loop]);  
  31.                       
  32.             for (int k = cols-1-loop-1; k>=loop; k--)  
  33.                 retVector.push_back(matrix[rows-1-loop][k]);  
  34.               
  35.             for (int l = rows-1-loop-1; l>=loop+1; l--)  
  36.                 retVector.push_back(matrix[l][loop]);  
  37.         }  
  38.           
  39.         if (maxLoop%2)  
  40.         {  
  41.             if (rows < cols)  
  42.             {  
  43.                 for (int i=maxLoop/2; i<cols-maxLoop/2; i++)  
  44.                     retVector.push_back(matrix[maxLoop/2][i]);  
  45.             }  
  46.             else if (rows > cols)  
  47.             {  
  48.                 for (int j=maxLoop/2; j<rows-maxLoop/2; j++)  
  49.                     retVector.push_back(matrix[j][maxLoop/2]);  
  50.             }  
  51.             else  
  52.             {  
  53.                 retVector.push_back(matrix[maxLoop/2][maxLoop/2]);  
  54.             }  
  55.         }  
  56.         return retVector;  
  57.     }  
  58. };  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值