C++ Solution


  • 0
    Y
    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            
            vector<vector<int>> result(n, vector<int>(n, 0));
            int rowBegin=0, rowEnd=n-1;
            int colBegin=0, colEnd=n-1;
            int k=1;
            while (rowBegin <= rowEnd && colBegin <= colEnd) {
                
                // from left to right
                for (int j=colBegin; j<=colEnd; j++) {
                    result[rowBegin][j] = k++;
                }
                rowBegin++;
                // from top to bottom
                for (int i=rowBegin; i<=rowEnd; i++) {
                    result[i][colEnd] = k++;
                }
                colEnd--;
                // from right to left
                for (int j=colEnd; j>=colBegin; j--) {
                    result[rowEnd][j] = k++;
                }
                rowEnd--;
                // from bottom to top
                for (int i=rowEnd; i>=rowBegin; i--) {
                    result[i][colBegin] = k++;
                }
                colBegin++;
            }
            return result;
            
        }
    };
    

Log in to reply
 

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