leetcode:Spiral Matrix II

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;
}

测试结果:



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/what_lei/article/details/52373464
文章标签: C++ leetcode
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭