zoukankan      html  css  js  c++  java
  • leetcode[59]Spiral Matrix II

    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 ]
    ]
    class Solution {
    public:
    void generate1(int icount, vector<vector<int>> &res, int left, int right, int up, int down)
    {
    /*
        if (icount==res.size()*res[0].size())
            return;
    */
        if (left>right||up>down)
            return;
        if (up==down)
        {
            for (int j=left;j<=right;j++)
            {
                icount++;
                res[up][j]=icount;
            }
            return;
        }
        if (left==right)
        {
            for (int i=up;i<=down;i++)
            {
                icount++;
                res[i][left]=icount;
            }
            return;
        }
        for (int j=left;j<right;j++)
        {
            icount++;
            res[up][j]=icount;
        }
        for (int i=up;i<down;i++)
        {
            icount++;
            res[i][right]=icount;
        }
        for (int j=right;j>left;j--)
        {
            icount++;
            res[down][j]=icount;
        }
        for(int i=down;i>up;i--)
        {
            icount++;
            res[i][left]=icount;
        }
        generate1(icount, res, left+1, right-1, up+1, down-1);
    }
    vector<vector<int> > generateMatrix(int n) 
    {    
        vector<vector<int>> res;
        if(n==0)return res;
        vector<int> temp;
        temp.insert(temp.end(),n,INT_MIN);
        res.insert(res.end(),n,temp);
        generate1(0,res,0,n-1,0,n-1);
        return res;
    }
    };
  • 相关阅读:
    Single Threaded Execution
    多线程(第三天)
    多线程(第二天)
    IE中float:right单独一行
    web.xml配置
    java调用asmx的webservice
    跨域访问
    jsp页面导入jstl标签
    搜索dwr做即时聊天的时候看到的问题
    LigerUI tree在ie下显示不出来/LigerUI 控件在ie下错乱
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281526.html
Copyright © 2011-2022 走看看