The easy understanding concise solution, origin from the Spiral Matrix I problem


  • 0
    S
    vector<vector<int> > generateMatrix(int n) {
            vector<vector<int> > ans(n, vector<int>(n, 0));
            if (n <= 0) return ans;
            int x0 = 0, x1 = n - 1;
            int y0 = 0, y1 = n - 1;
            int k = 0;
            
            while (x0 <= x1 && y0 <= y1) {
                // gen right side
                for (int j = y0; j <= y1; ++j)
                    ans[x0][j] = ++k;
                x0++;
                
                // gen down side
                for (int i = x0; i <= x1; ++i)
                    ans[i][y1] = ++k;
                y1--;
                
                // gen left side
                if (x0 > x1) break;
                for (int j = y1; j >= y0; --j)
                    ans[x1][j] = ++k;
                x1--;
                
                // gen up side
                if (y0 > y1) break;
                for (int i = x1; i >= x0; --i)
                    ans[i][y0] = ++k;
                y0++;
            }
            
            return ans;
        }

Log in to reply
 

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