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 ] ]
依旧是dfs问题,代码如下所示:
1 class Solution { 2 public: 3 vector<vector<int>> generateMatrix(int n) { 4 vector<vector<int>>ret(n, vector<int>(n, 0)); 5 vector<vector<bool>>mark(n, vector<bool>(n,false)); 6 if(!n) return ret; 7 dfs(ret, mark, 0, -1, n, 0, 1); 8 return ret; 9 } 10 11 void dfs(vector<vector<int>> & ret, vector<vector<bool>> & mark, int i, int j, int n, int curr, int currVal) 12 { 13 for(int k = 0; k < 4; ++k){ 14 int dirct = (curr + k) % 4; 15 int ii = i + drct[dirct][0]; 16 int jj = j + drct[dirct][1]; 17 if(ii >= 0 && ii < n && 18 jj >= 0 && jj < n && 19 mark[ii][jj] == false){ 20 mark[ii][jj] = true; 21 ret[ii][jj] = currVal; 22 dfs(ret, mark, ii, jj, n, dirct, currVal + 1); 23 } 24 25 } 26 } 27 28 private: 29 vector<vector<int>>drct = {{0,1},{1,0},{0,-1},{-1,0}}; 30 };
代码写的比较乱,凑合着看哈哈