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]
]
Algorithm: the algorithm is divided into four directions, with scanning in the upper right and lower left. If you can enter a number, you can change the direction. This question is not difficult, but it is prone to small errors. The Code is as follows:
1 class Solution { 2 public: 3 vector<vector<int>> result; 4 vector<vector<int> > generateMatrix(int n) { 5 int total=n*n; 6 int x=0; 7 int y=0; 8 int direction=0; 9 result.clear();10 for(int i=0;i<n;i++)11 {12 vector<int> nn;13 result.push_back(nn);14 for(int j=0;j<n;j++)15 {16 result[i].push_back(0);17 }18 }19 for(int i=1;i<=total;i++)20 {21 if(0==result[x][y])22 {23 result[x][y]=i;24 }25 else if(0==direction)26 {27 if(y+1<=n-1&&0==result[x][y+1])28 {29 result[x][y+1]=i;30 y++;31 }32 else 33 {34 direction=1;35 36 i--;37 }38 }39 else if(1==direction)40 {41 if(x+1<=n-1&&0==result[x+1][y])42 {43 result[x+1][y]=i;44 x++;45 }46 else47 {48 direction=2;49 i--;50 }51 }52 else if(2==direction)53 {54 if(y-1>=0&&0==result[x][y-1])55 {56 result[x][y-1]=i;57 y--;58 }59 else60 {61 direction=3;62 i--;63 }64 }65 else if(3==direction)66 {67 if(x-1>=0&&0==result[x-1][y])68 {69 result[x-1][y]=i;70 x--;71 }72 else73 {74 direction=0;75 i--;76 }77 }78 }79 return result;80 }81 };
Spiral matrix II <leetcode>