LeetCode-59-Spiral Matrix II

算法描述:

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

解题思路:模拟,注意边界。

    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> results(n,vector<int>(n,0));
        int rowBegin = 0;
        int rowEnd = n-1;
        int colBegin = 0;
        int colEnd = n-1;
        int index = 1;
        while(rowBegin <= rowEnd && colBegin <=colEnd){
            for(int i=colBegin; i <= colEnd; i++) results[rowBegin][i] = index++;
            rowBegin++;
            for(int i=rowBegin; i <= rowEnd; i++) results[i][colEnd] = index++;
            colEnd--;
            if(rowBegin <= rowEnd && colBegin <= colEnd){
                for(int i=colEnd; i >= colBegin; i--) results[rowEnd][i] = index++;
                rowEnd--;
                for(int i=rowEnd; i >= rowBegin; i--) results[i][colBegin] = index++;
                colBegin++;
            }
        }
        return results;
    }

猜你喜欢

转载自www.cnblogs.com/nobodywang/p/10337300.html
今日推荐