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].
螺旋输出MxN矩阵 【注意是MxN】
class Solution {
public:
void output(vector<int>&result, vector<vector<int> >&matrix, int i, int j, int rows, int cols){
if(rows<1 || cols<1)return;
if(rows == 1){
for(int y=j; y<j+cols; y++){
result.push_back(matrix[i][y]);
}
return;
}
if(cols==1){
for(int x=i; x<i+rows; x++){
result.push_back(matrix[x][j]);
}
return;
}
//输出上边行
int x=i, y=j;
while(y<j+cols){
result.push_back(matrix[x][y]);
y++;
}
//输出右边行
x=i+1; y=j+cols-1;
while(x<i+rows){
result.push_back(matrix[x][y]);
x++;
}
//输出下边行
x=i+rows-1; y=j+cols-2;
while(y>=j){
result.push_back(matrix[x][y]);
y--;
}
//输出左边行
x=i+rows-2; y=j;
while(x>i){
result.push_back(matrix[x][y]);
x--;
}
//输出内圈
output(result, matrix, i+1, j+1, rows-2, cols-2);
}
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int>result;
int rows=matrix.size();
if(rows==0)return result;
int cols=matrix[0].size();
output(result,matrix, 0, 0,rows, cols);
return result;
}
};LeetCode: Spiral Matrix [058],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26739481