Spiral Matrix
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]
.
Problem-solving idea: to find a matrix loop around a rectangular output element. We can use the rules of the matrix four edges to output each element. Upper left---right, upper right---bottom right, bottom right---bottom left, bottom left---left, output rectangle four edges in this order, rectangle from small to large, until all elements are output. The code is as follows:
Class Solution {public: vector<int> spiralorder (vector<vector<int>>& matrix) { vector <int> Res; if (Matrix.size () ==0) return res; int n=matrix.size (); int m=matrix[0].size (); for (int row=0;row<n/2+1;row++) {int I=row;int j=i;for (j=i;j< (M-row) ; j + +) {Res.push_back (matrix[i][j]), if (res.size () = = (N*m)) {return res;}} J--;for (i=row+1;i< (n-row); i++) {res.push_back (matrix[i][j]), if (res.size () = = (N*m)) {return res;}} I--;for (j=j-1;j>=row;j--) {res.push_back (matrix[i][j]), if (res.size () = = (N*m)) {return res;}} J++;for (i=i-1;i>=row+1;i--) {res.push_back (matrix[i][j]), if (res.size () = = (N*m)) {return res;}} return res; }};
Spiral Matrix II
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]]
Class Solution {public: vector<vector<int>> generatematrix (int n) { int x=0;vector<vector< Int>> res;vector<int> Temp (n,0); for (int i=0;i<n;i++) {res.push_back (temp);} for (int row=0;row<n/2+1;row++) {int I=row;int j=i;for (j=i;j< (N-row); j + +)//left---right {res[i][j]=++x;} J--;for (i=row+1;i< (n-row); i++)//Upper---{res[i][j]=++x;} I--;for (j=j-1;j>=row;j--)//Right---left {res[i][j]=++x;} J++;for (i=i-1;i>=row+1;i--)//down---{res[i][j]=++x;}} return res; }};
Spiral matrix && Spiral Matrix II