A short C++ solution


  • 1
    L
    class Solution {
    public:
    	vector<vector<int>> generateMatrix(int n) {
    		vector<vector<int> > mat(n, vector<int>(n));
    		int r = 0, c = -1, x = 1;
    		const int g[5] = { 0, 1, 0, -1, 0 };
    		for (int b = 0, i = 0; n > 0; n -= (b ^= 1), i = (++i % 4)) {
    			for (int s = 0; s < n; s++) {
    				mat[r += g[i]][c += g[i+1]] = x++;
    			}
    		}
    		return mat;
    	}
    };

  • 0
    L

    the outer loop produces the step size of each side e.g., for 5x5 , it'll be 5,4,4,3,2,2,1
    notice the decrements are alternating between 1 and 0, which is what b^=1 produce
    the outer loop also produces a state variable i, representing which side it's filling the number for, and whose value can take on 0,1,2,3, g[5] stores the row/column index increment for each side, notice the increment for row and column index follows a similar pattern, except row lead column index by 1/4 cycle.
    finnaly the inner loop just go thru 1 side and fill in the #s with correct index


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.