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

[leetcode-59-Spiral Matrix II]

时间:2017-06-01 21:42:15      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:左右   leetcode   square   --   row   span   class   nts   turn   

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

思路:

4个方向变量上下左右控制边界。

vector<vector<int>> generateMatrix(int n) {
            
         vector<vector<int>>matrix(n,vector<int>(n,0));
         int up = 0, down = n - 1, left = 0, right = n - 1 ,k =1;
         while (1)
         {
             for (int col = left; col <= right; col++)matrix[up][col] = k++;
             if (++up>down)break;
             for (int row = up; row <= down; row++)matrix[row][right] = k++;
             if (--right < left)break;
             for (int col = right; col >= left; col--)matrix[down][col] = k++;
             if (--down < up)break;
             for (int row = down; row >= up; row--)matrix[row][left] = k++;
             if (++left>right)break;
         }
         return matrix; 
    }

 

[leetcode-59-Spiral Matrix II]

标签:左右   leetcode   square   --   row   span   class   nts   turn   

原文地址:http://www.cnblogs.com/hellowooorld/p/6930727.html

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