题目描述:
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]
.
解题思路:
这题的思路没有什么好说的,就是一圈一圈添加元素进数组。只是要注意row和col是不一样的情况和相同时是偶数的情况。
代码:
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int>>& matrix) { 4 vector<int> ret; 5 if(matrix.size()==0) 6 return ret; 7 int row = matrix.size(); 8 int col = matrix[0].size(); 9 int times = row>col?col/2:row/2; 10 for(int i = 0; i < times; i++){ 11 for(int j = i; j < col-1-i; j++) 12 ret.push_back(matrix[i][j]); 13 for(int j = i; j < row-1-i; j++) 14 ret.push_back(matrix[j][col-1-i]); 15 for(int j = col-1-i; j > i; j--) 16 ret.push_back(matrix[row-1-i][j]); 17 for(int j = row-1-i; j > i; j--) 18 ret.push_back(matrix[j][i]); 19 } 20 int mod = row>col?col%2:row%2; 21 if(mod == 1){ 22 if(row == col) 23 ret.push_back(matrix[times][times]); 24 else if(col > row) 25 for(int i = times; i < col-times; i++) 26 ret.push_back(matrix[times][i]); 27 else 28 for(int i = times; i < row-times; i++) 29 ret.push_back(matrix[i][times]); 30 } 31 return ret; 32 } 33 };