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

【leetcode】Spiral Matrix II

时间:2015-02-07 17:14:43      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:

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

与Spiral Matrix相似,给定方阵的维度n,返回一个螺旋矩阵。

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector< vector<int> > matrix(n, vector<int>(n));
		//begin_row is the row number, end_row is the remaind size of each row
		int begin_row = 0, end_row = n - 1;
		//begin_col is the col number,end_col is the remaind size of each col
		int begin_col = 0, end_col = n - 1;

		int num = 1;
		while(true){
			for(int i = begin_row; i <= end_row; ++i)//left to right
				matrix[begin_row][i] = num++;
			if(++begin_col > end_col) break;

			for(int i = begin_col; i <= end_col; ++i)//up to down
				 matrix[i][end_row] = num++;
			if(begin_row > --end_row) break;

			for(int i = end_row; i >= begin_row; --i)//right to left
				matrix[end_col][i] = num++;
			if(begin_col > --end_col) break;

			for(int i = end_col; i >= begin_col; --i)//bottom to up
				matrix[i][begin_row] = num++;
			if(++begin_row > end_row) break;
		}

		return matrix;
    }
};

 

 



【leetcode】Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/zxy1992/p/4279001.html

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