1. 程式人生 > >LeetCode-59-Spiral Matrix II

LeetCode-59-Spiral Matrix II

output led while tor inpu ive elements rate class

算法描述:

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; }

LeetCode-59-Spiral Matrix II