leetcode:Spiral Matrix II

原创 2016年08月30日 22:32:57

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

测试结果:



版权声明:本文为博主原创文章,未经博主允许不得转载。

牛客:剑指offer:顺时针打印矩阵 (Java)(同leetcode的spiral matrix i 和ii)

题目描述: 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:1 2 3 45 6 7 89 10 11 1213 14 15 16则依次打印出数字1,2,3,4,...

[LeetCode]--59. Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.For e...

leetcode--Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...

【leetcode】Spiral Matrix II

一、问题描述 Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral...

Leetcode NO.59 Spiral Matrix II

本题题目要求如下: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spi...

【LeetCode】59. Spiral Matrix II 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51416037Subject 出处:https://leetcode.com/pro...

LeetCode | 59. Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.For e...

LeetCode059 Spiral Matrix II

详细见:leetcode.com/problems/spiral-matrix-ii Java Solution: github package leetcode; public c...
  • zxwtry
  • zxwtry
  • 2017年04月12日 21:08
  • 72

Leetcode 59. Spiral Matrix II

题目描述 Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral orde...

LeetCode54/59 Spiral Matrix I/II

一:Spiral Matrix I 题目: Given a matrix of m x n elements (m rows, n columns), return all elements ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode:Spiral Matrix II
举报原因:
原因补充:

(最多只允许输入30个字)