标签:
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]
.
思路:模拟,一圈圈地环绕,直到停止。
代码:
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int>>& matrix) { 4 vector<int> res; 5 if(matrix.size()==0) return res; 6 if(matrix[0].size()==0) return res; 7 int m=matrix.size(),n=matrix[0].size(),i=0,j=0; 8 while(n>0&&m>0){ 9 res.push_back(matrix[i][j]); 10 n--; 11 m--; 12 int step=n; 13 while(step>0){ 14 res.push_back(matrix[i][++j]); 15 step--; 16 } 17 step=m; 18 while(step>0){ 19 res.push_back(matrix[++i][j]); 20 step--; 21 } 22 if(m>0&&n>0){//判断有没有剩余的半圈 23 step=n--;//得到下一圈的n 24 while(step>0){ 25 res.push_back(matrix[i][--j]); 26 step--; 27 } 28 step=--m;//得到下一圈的m 29 while(step>0){ 30 res.push_back(matrix[--i][j]); 31 step--; 32 } 33 j++; 34 } 35 } 36 return res; 37 } 38 };
标签:
原文地址:http://www.cnblogs.com/Deribs4/p/5728429.html