LeetCode(59)SPiral Matrix II

2894 ワード

タイトル
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example, Given n = 3,
You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
ぶんせき
54題のSpiral Matrixと似たような問題で,2次元行列に螺旋状の付与を行った.
ACコード
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int> > ret(n,vector<int>(n , 0));
        if (n <= 0)
            return ret;

        int index = 1 , row = n-1 , col = n-1;
        for (int x = 0, y = 0; x <= row && y <= col; x++, y++)
        {
            //       
            for (int j = y; j <= col; ++j , index++)
                ret[x][j] = index;

            //        
            for (int i = x + 1; i <= row; ++i,index++)
                ret[i][col] = index;

            //        
            for (int j = col - 1; j >= y && x != row; --j, index++)
                ret[row][j] = index;

            //        
            for (int i = row - 1; i > x && y != col; --i, index++)
                ret[i][y] = index;

            //        
            row--;
            col--;

        }//for
        return ret;
    }
};

GitHubテストプログラムソースコード