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 int min(int a, int b){ 2 if(a < b) 3 return a; 4 return b; 5 } 6 vector<int> spiralOrder(vector<vector<int> > &matrix) { 7 // IMPORTANT: Please reset any member data you declared, as 8 // the same Solution instance will be reused for each test case. 9 vector<int> result; 10 result.clear(); 11 int m = matrix.size(); 12 if(m == 0) 13 return result; 14 int n = matrix[0].size(); 15 if(n == 0) 16 return result; 17 int i,j; 18 for(i = 0; i < min(m,n)/2; i++){ 19 for(j = i; j < n-1-i; j++) 20 result.push_back(matrix[i][j]); 21 for(j = i; j < m-1-i; j++) 22 result.push_back(matrix[j][n-1-i]); 23 for(j = n-1-i; j > i; j--) 24 result.push_back(matrix[m-1-i][j]); 25 for(j = m-1-i; j > i; j--) 26 result.push_back(matrix[j][i]); 27 } 28 if(min(m,n)%2 == 1){ 29 if(m < n){ 30 for(i = m/2; i < n-m/2; i++) 31 result.push_back(matrix[m/2][i]); 32 } 33 else{ 34 for(i = n/2; i < m-n/2; i++) 35 result.push_back(matrix[i][n/2]); 36 } 37 } 38 return result; 39 }