码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-59-Spiral Matrix II

时间:2019-01-30 13:11:51      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:code   col   generate   nbsp   osi   思路   from   while   for   

算法描述:

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

标签:code   col   generate   nbsp   osi   思路   from   while   for   

原文地址:https://www.cnblogs.com/nobodywang/p/10337300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!