A neat C++ solution using directions


  • 0
    C

    This solution is inspired from stellari's work on Spiral I, but the process is reverted :)

    vector<vector<int>> generateMatrix(int n) {
    	vector<vector<int>> ret(n, vector<int>(n, 0));
    	vector<vector<int>> dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    	vector<int> steps = {n, n-1};
    	int r = 0, c = -1, d = 0, cnt = 1;
    	while(steps[d % 2]){
    		for (int i = 0; i < steps[d % 2]; i++){
    			r += dir[d][0]; c += dir[d][1];
    			ret[r][c] = cnt ++;
    		}
    		
    		steps[d % 2] --;
    		d = (d + 1) % 4;
    	}
    
    	return ret;
    }
    

  • 0
    R
    //C++ concise solution
         vector<vector<int>> generateMatrix(int n) {
                vector<vector<int>> m(n,vector<int>(n));
                int count=0;
                for(int i=0;i<n-i;i++)
                {
                    if(count) count=m[i][i-1];
                    for(int j=i;j<n-i-1;j++)
                    {
                        count++;
                        m[n-j-1][i]=count+3*(n-2*i-1);
                        m[n-i-1][n-j-1]=count+2*(n-2*i-1);
                        m[j][n-i-1]=count+n-2*i-1;
                        m[i][j]=count;
                        
                    }
                }
                if(n%2 ==1) m[n/2][n/2]=n*n;
                return m;
                
            }

Log in to reply
 

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