程序员人生 网站导航

Leetcode 59 Spiral Matrix II

栏目:php教程时间:2016-12-12 15:17:39

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 ] ]
方阵蛇形填数

和上1道蛇形取数差不多。

http://blog.csdn.net/accepthjp/article/details/52577112

class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<int> row(n,0); vector<vector<int>> result(n,row); int rows=n,cols=n,cnt=0; for(int x=0,y=0;x<rows && y<cols;x++,y++) { for(int i=y;i<cols;i++) result[x][i]=++cnt; for(int i=x+1;i<rows;i++) result[i][cols⑴]=++cnt; for(int i=cols⑵;i>=y;i--) result[rows⑴][i]=++cnt; for(int i=rows⑵;i>x;i--) result[i][y]=++cnt; rows--; cols--; } return result; } };


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐