关闭

leetcode:Spiral Matrix II

标签: C++leetcode
142人阅读 评论(0) 收藏 举报
分类:

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

即,给定矩阵大小,返回螺旋矩阵

c++实现:

#include <iostream>
#include <vector>

using namespace std;
vector<vector<int> > generateMatrix(int n)
{
	vector< vector<int> > matrix(n, vector<int>(n));

	if (n == 0) 
		return matrix;

	int beginX = 0, endX = n - 1;
	int beginY = 0, endY = n - 1;
	int num = 1;
	while (true) 
	{
		for (int j = beginX; j <= endX; ++j) 
			matrix[beginY][j] = num++;
		if (++beginY > endY) 
			break;
		for (int i = beginY; i <= endY; ++i) 
			matrix[i][endX] = num++;
		if (beginX > --endX) 
			break;
		for (int j = endX; j >= beginX; --j) 
			matrix[endY][j] = num++;
		if (beginY > --endY) 
			break;
		for (int i = endY; i >= beginY; --i) 
			matrix[i][beginX] = num++;
		if (++beginX > endX)
			break;
	}
	return matrix;
}
int main()
{
	vector<vector<int>> vec;
	int n=3;
	vec=generateMatrix(n);
	vector<vector<int>>::iterator pp;  
    vector<int>::iterator it;  
    for(pp=vec.begin();pp<vec.end();pp++)  
    {  
        for (it=(*pp).begin();it<(*pp).end();it++)  
        {  
            cout<<*it<<" ";  
        }  
        cout<<endl;  
    }  
	
	return 0;
}

测试结果:



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:58372次
    • 积分:1182
    • 等级:
    • 排名:千里之外
    • 原创:62篇
    • 转载:7篇
    • 译文:0篇
    • 评论:9条
    最新评论