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问题,代码如下所示:

 class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>>ret(n, vector<int>(n, ));
vector<vector<bool>>mark(n, vector<bool>(n,false));
if(!n) return ret;
dfs(ret, mark, , -, n, , );
return ret;
} void dfs(vector<vector<int>> & ret, vector<vector<bool>> & mark, int i, int j, int n, int curr, int currVal)
{
for(int k = ; k < ; ++k){
int dirct = (curr + k) % ;
int ii = i + drct[dirct][];
int jj = j + drct[dirct][];
if(ii >= && ii < n &&
jj >= && jj < n &&
mark[ii][jj] == false){
mark[ii][jj] = true;
ret[ii][jj] = currVal;
dfs(ret, mark, ii, jj, n, dirct, currVal + );
} }
} private:
vector<vector<int>>drct = {{,},{,},{,-},{-,}};
};

代码写的比较乱,凑合着看哈哈

05-23 20:35