Given an integerN, Generate a square matrix filled with elements from 1N2 in spiral order.
For example, givenN=3
,
You shoshould return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
Class solution {public: vector <int> generatematrix (int n) {vector <int> V (n, 0); vector <int> res (n, v); int Col = (n + 1)/2-1; // The row and column number of the end point int ROW = n/2; int num = 1; int rowstart = 0, rowend = n-1, colstart = 0, colend = n-1; Int J = colstart, I = rowstart; while (1) {for (j = colstart; j <= colend; j ++) {res [I] [J] = num ++;} J = J-1; if (I = row & J = col) break; rowstart ++; j = colend; for (I = rowstart; I <= rowend; I ++) {res [I] [J] = num ++;} colend --; I = rowend; For (j = colend; j> = colstart; j --) {res [I] [J] = num ++;} J = J + 1; if (I = row & J = col) break; rowend --; j = colstart; for (I = rowend; I> = rowstart; I --) {res [I] [J] = num ++;} colstart ++; I = rowstart ;}// end while return res ;}};
[Leetcode] spiral matrix II