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 ] ]
]
算法:分四个方向,右下左上,分别扫描,能填数字就填,不能填就改变方向,该题不难,但是容易有小错误,代码如下:
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 else 47 { 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 else 60 { 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 else 73 { 74 direction=0; 75 i--; 76 } 77 } 78 } 79 return result; 80 } 81 };