Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X 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]
.
Use left, top, right, bottom to record boundary conditions.
1vector<int> Spiralorder (vector<vector<int> > &matrix)2 {3vector<int>ret;4 intm =matrix.size ();5 if(M <=0)6 returnret;7 intn = matrix[0].size (), i =0, j =0;8 intleft =0, right = N-1, top =0, bottom = M-1;9 Ten while(true) One { Ai = top, j =Left ; - while(J <=Right ) -Ret.push_back (matrix[i][j++]); the if(++top > Bottom) Break; - -i = top, j =Right ; - while(I <=bottom) +Ret.push_back (matrix[i++][j]); - if(--right < left) Break; + Ai = bottom, j =Right ; at while(J >=Left ) -Ret.push_back (matrix[i][j--]); - if(--bottom < top) Break; - -i = bottom, j =Left ; - while(I >=top) inRet.push_back (matrix[i--][j]); - if(++left > right) Break; to } + - returnret; the}
Given an integer n, generate a square matrix filled with elements from 1 to n2 in Spiral order.
For example,
Given N = 3
,
You should return the following matrix:
[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
1vector<vector<int> > Generatematrix (intN)2 {3vector<vector<int> >Matrix;4 if(N <=0)5 returnMatrix;6 intleft =0, right = N-1, top =0, bottom = n-1, I, j, k =1;7vector<int>Line (n);8 for(i =0; I < n; i++)9 Matrix.push_back (line);Ten while(true) One { Ai = top, j =Left ; - while(J <=Right ) -Matrix[i][j++] = k++; the if(++top > Bottom) Break; - -i = top, j =Right ; - while(I <=bottom) +MATRIX[I++][J] = k++; - if(--right < left) Break; + Ai = bottom, j =Right ; at while(J >=Left ) -matrix[i][j--] = k++; - if(--bottom < top) Break; - -i = bottom, j =Left ; - while(I >=top) inMATRIX[I--][J] = k++; - if(++left > right) Break; to } + - returnMatrix; the}
Leetcode. Spiral Matrix