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

[LeetCode]59.Spiral Matrix II

时间:2015-02-04 23:29:21      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:经典面试题   leetcode   数组   

【题目】

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

【分析】

模拟

【代码】

    /**------------------------------------
    *   日期:2015-02-04
    *   作者:SJF0115
    *   题目: 59.Spiral Matrix II
    *   网址:https://oj.leetcode.com/problems/spiral-matrix-ii/
    *   结果:AC
    *   来源:LeetCode
    *   博客:
    ---------------------------------------**/
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;

    class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            vector<vector<int> > matrix(n,vector<int>(n,0));
            if(n <= 0){
                return matrix;
            }//if
            int count = n * n;
            int index = 1;
            int x = 0,y = -1;
            while(index <= count){
                // right
                ++y;
                while(y < n && matrix[x][y] == 0){
                    matrix[x][y++] = index;
                    ++index;
                }//while
                --y;
                // down
                ++x;
                while(x < n && matrix[x][y] == 0){
                    matrix[x++][y] = index;
                    ++index;
                }//while
                --x;
                // left
                --y;
                while(y >= 0 && matrix[x][y] == 0){
                    matrix[x][y--] = index;
                    ++index;
                }//while
                ++y;
                // up
                --x;
                while(x >= 0 && matrix[x][y] == 0){
                    matrix[x--][y] = index;
                    ++index;
                }//while
                ++x;
            }//while
            return matrix;
        }
    };

    int main(){
        Solution s;
        int n = 5;
        vector<vector<int> > matrix = s.generateMatrix(n);
        // 输出
        for(int i = 0;i < n;++i){
            for(int j = 0;j < n;++j){
                cout<<matrix[i][j]<<"  ";
            }//for
            cout<<endl;
        }//for
        return 0;
    }

技术分享

[LeetCode]59.Spiral Matrix II

标签:经典面试题   leetcode   数组   

原文地址:http://blog.csdn.net/sunnyyoona/article/details/43497373

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