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

[leetcode]Spiral Matrix II

时间:2015-12-11 15:03:35      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

问题叙述性说明:

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 ]
]

基本思路:

本题是上一篇《Spiral Matrix》的变形。能够採用相同的遍历方法为其赋值。创建旋转矩阵。


代码:

vector<vector<int> > generateMatrix(int n) { //C++
        vector<vector<int> >result;
        if(n <=0 )
            return result;
        
        for(int i = 0; i < n; i++){
            vector<int> tmp(n,0);
            result.push_back(tmp);
        }
        
        int rowBegin = 0;
        int rowEnd   = n-1;
        int colBegin = 0;
        int colEnd   = n-1;
        
        int count = 1;
        while(rowBegin <= rowEnd && colBegin <= colEnd){
            //to right
            for(int j = colBegin; j <= colEnd; j++)
                result[rowBegin][j] =count++;
            rowBegin++;
            
            //to down
            for(int j = rowBegin; j <= rowEnd; j++)
                result[j][colEnd] = count++;
            colEnd--;
            
            //to left
            if(rowBegin <= rowEnd){
                for(int j = colEnd; j >= colBegin; j--)
                    result[rowEnd][j] = count++;
            }
            rowEnd--;
            
            //to up
            if(colBegin <= colEnd){
                for(int j = rowEnd; j >= rowBegin; j--)
                    result[j][colBegin] = count++;
            }
            colBegin++;
        }
        return result;
    }


[leetcode]Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/yxwkf/p/5038791.html

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