leetcode 59:Spiral Matrix II

原创 2015年11月18日 21:15:57

题目:

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比较相似,具体思路见Spiral Matrix

时间复杂度:O(n^2)


实现如下:

class Solution {
public:
	vector<vector<int>> generateMatrix(int n) {
		vector<vector<int>> result(n, vector<int>(n, 0));
		int left = 0, right = n - 1, up = 0, down = n - 1, count = 1;
		while (left <= right)
		{
			int column = left;
			for (; column <= right; ++column) result[up][column] = count++;
			++up;
			int row = up;
			for (; row <= down; ++row) result[row][right] = count++;
			--right;
			if (up <= down)
			{
				for (column = right; column >= left; --column) result[down][column] = count++;
				--down;
			}
			if (left <= right)
			{
				for (row = down; row >= up; --row) result[row][left] = count++;
				++left;
			}
		}
		return result;
	}
};


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

[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 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...

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#59. Spiral Matrix II

题目:给定一个整数n,以螺旋形将1到n^2填充螺旋矩阵

LeetCode 54/59. Spiral Matrix i, ii

1. 题目描述54 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix ...

leetcode 59. Spiral Matrix II

我在这里用了和leetcode 54 一样的思路开辟了一个和原矩阵同样大小的矩阵temp来存放是否输出过的标志位,然后按照向右,向左,向上,向下的顺时针顺序构造矩阵。 下面是这两道题的代码:...

[LeetCode]59.Spiral Matrix II

【题目】 Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral orde...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 59:Spiral Matrix II
举报原因:
原因补充:

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