Simple solution by checking the range before move forward.

  • 0
    class Solution {
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> v(n, vector<int>(n, 0));
        int total=n*n;
        int i=0, j=-1;
        int cnt=0;
            while(j<n-1 && v[i][j+1]==0) v[i][++j]=++cnt;
            while(i<n-1 && v[i+1][j]==0) v[++i][j]=++cnt;
            while(j>0  && v[i][j-1]==0) v[i][--j]=++cnt;
            while(i>0  && v[i-1][j]==0) v[--i][j]=++cnt;
        return v;

Log in to reply

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