Leetcode 59. 螺旋矩阵 II

水题T*T

class Solution {
public:
    int a[25][25], dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    vector<vector<int>> generateMatrix(int n) {
	    int x = 1, y = 1, cnt = 0, d = 0;
	    while(cnt < n * n) {
            while(!a[x][y]) {
                a[x][y] = ++cnt;
                x += dir[d][0], y += dir[d][1];
                if(x == 0 || y == 0 || x == n + 1 || y == n + 1 || a[x][y]) {
                    x -= dir[d][0], y -= dir[d][1];
                    d = (d + 1) % 4;
                    x += dir[d][0], y += dir[d][1];
                    break;
                }
            }
	    }
        vector<vector<int> > ans;
        for(int i = 1; i <= n; i++) {
            vector<int> tmp;
		    for(int j = 1; j <= n; j++) {
			    tmp.push_back(a[i][j]);
		    }
            ans.push_back(tmp);
	    }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/lipoicyclic/p/14541507.html