zoukankan      html  css  js  c++  java
  • 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:
        vector<vector<int> > generateMatrix(int n) {
            vector<vector<int> >re;
            for(int i = 0 ;i < n; i++)
            {
                vector <int> temp(n,0);
                re.push_back(temp);
            }
            int direction =0;   //0 right ,1 down ,2 left, 3 up
            int length = n;
            int x = 0;
            int y = 0;
            int step = 0;
            for(int i = 1 ; i <= n*n ; i++)
            {
                re[x][y] = i;
                step++;
                if(step == length)  //should turn
                {
                    direction = (direction + 1)%4;
                    if(direction == 0)
                    {
                        y = y+1;
                        step = 0;
                    }
                    else if(direction == 1)
                    {
                        x = x+1;
                        length--;
                        step = 0;
                    }
                    else if(direction == 2)
                    {
                        y = y-1;
                        step = 0;
                    }
                    else
                    {
                        x = x-1;
                        length--;
                        step = 0;
                    }
                }
                else
                {
                    if(direction == 0) y = y+1;
                    else if(direction == 1)x = x+1;
                    else if(direction == 2)y = y-1;
                    else x = x-1;
                }
                
            }
            return re;
        }
    };
    

      

  • 相关阅读:
    18周个人总结
    十六周个人总结
    排球积分规则程序
    十四周软件工程总结
    本周总结
    排球积分规则
    我的计算机生涯
    排球比赛记分员
    《怎样成为一个高手》观后感
    冲刺作业
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3595609.html
Copyright © 2011-2022 走看看