54. Spiral Matrix(劍指offer 19)
阿新 • • 發佈:2019-01-04
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
注意只有一行或者只有一列的情況
if (r1 < r2 && c1 < c2) {//避免只有一行,c1==c2的情況,避免只有一列,r1==r2的情況
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> list ; if(matrix.size()==0) return list; int rows =matrix.size(); int cols = matrix[0].size(); int c1 = 0,c2 = cols-1; int r1 = 0,r2 = rows-1; while(r1<=r2&&c1<=c2){ for(int c=c1;c<=c2;c++) list.push_back(matrix[r1][c]); for(int r=r1+1;r<=r2;r++) list.push_back(matrix[r][c2]);if (r1 < r2 && c1 < c2) {//避免只有一行,c1==c2的情況,避免只有一列,r1==r2的情況 for(int c=c2-1;c>=c1+1;c--) list.push_back(matrix[r2][c]); for(int r=r2;r>=r1+1;r--) list.push_back(matrix[r][c1]); } c1++;c2--;r1++;r2--; } return list; } };