Problem:
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 ] ]
Analysis:
Treat it as a simulation problem. Use a "dir" variable to represent the direction according to which to fill the data. In my solution, 1 for left, 2 for right, 3 for up and 4 for down.
Then according to this direction variable, we fill in element k into the position (i, j). i and j is updated each time after filling according to the direction. But after the update, the new (i, j) position may be either a position already been visited or simple out of boundry, then it's the signal to update the direction. The direction transition is as follows:
right -> down
down -> left
left -> up
up -> right
With all these updates, we can generate the spirla matrix.
Code:
1 class Solution { 2 public: 3 vector<vector<int> > generateMatrix(int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<vector<int> > res; 7 8 for (int i=0; i<n; i++) { 9 vector<int> tmp(n, 0); 10 res.push_back(tmp); 11 } 12 13 int sqr = n*n; 14 15 // dir 1 -> left, 2 -> right, 3 -> up, 4 -> down 16 int i=0, j=0, dir = 2; 17 for (int k=1; k<=sqr; k++) { 18 switch (dir) { 19 case 1: { 20 res[i][j--] = k; 21 if (j < 0 || res[i][j] != 0) { 22 j++; i--; 23 dir = 3; 24 } 25 break; 26 } 27 case 2: { 28 res[i][j++] = k; 29 30 if(j >= n || res[i][j] != 0) { 31 j--; i++; 32 dir = 4; 33 } 34 break; 35 } 36 case 3: { 37 res[i--][j] = k; 38 39 if (i < 0 || res[i][j] != 0) { 40 i++; j++; 41 dir = 2; 42 } 43 break; 44 } 45 case 4: { 46 res[i++][j] = k; 47 48 if (i >= n || res[i][j] != 0) { 49 i--; j--; 50 dir = 1; 51 } 52 break; 53 } 54 default: break; 55 } 56 } 57 58 return res; 59 } 60 61 };