leetcode 59

本以为会写很长时间结果一边就过了

这题与上一道螺旋矩阵思路基本相同,通过四个参数left right top bottom来完成螺旋的操作

vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n,vector<int>(n));
        int count=1;
        int left=0,top=0,right=n-1,bottom=n-1;
        while(1)
        {
            for(int i=left;i<=right;i++)
            {
                res[top][i] = count;
                count++;
            }
            if(++top>bottom)break;
            for(int i=top;i<=bottom;i++)
            {
                res[i][right] = count;
                count++;
            }
            if(--right<left)break;
            for(int i=right;i>=left;i--)
            {
                res[bottom][i]=count;
                count++;
            }
            if(--bottom<top)break;
            for(int i=bottom;i>=top;i--)
            {
                res[i][left]=count;
                count++;
            }
            if(++left>right)break;
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/TempterCyn/article/details/83757132