Clean C++ solution


  • 2
    H

    class Solution {
    public:
    vector<vector<int>> generateMatrix(int n) {

        int i=0, j=n-1;
        int cnt = 1;
        vector<vector<int>> m(n, vector<int>(n,0));
        while( i < j) {
            for(int k= i; k < j; k++) {
                m[i][k] = cnt++;
            }
            for(int k= i; k< j; k++) {
                m[k][j] = cnt++;
            }
            for(int k=i; k < j; k++) {
                m[j][n-1-k] = cnt++;
            }
            for(int k=i; k< j; k++) {
                m[n-1-k][i] = cnt++;
            }
            
            i++;
            j--;
        }
        
        if(i==j) {
            m[i][j] = cnt;
        }
        
        return m;
    }
    

    };


Log in to reply
 

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