LeetCode-----第五十九题----- 螺旋矩阵 II

螺旋矩阵 II

难度:中等

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

 

题目解析:

      螺旋遍历即可,每个数加1

 

参考代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

class Solution {
public:
	vector> generateMatrix(int n) {
		if (n < 1)
			return{};

		vector> res;
		res.resize(n);
		for (int i = 0; i < n; i++)
		{
			res[i].resize(n);
		}

		int left = 0;
		int right = n - 1;
		int up = 0;
		int down = n - 1;
		int index = 1;
		while (left <= right && up <= down && index <= n*n)
		{
			//上边
			for (int i = left; i <= right; i++)
			{
				res[up][i] = index;
				++index;
			}

			//右边
			for (int i = up + 1; i <= down; i++)
			{
				res[i][right] = index;
				++index;
			}

			//下边
			if (left != right)
			for (int i = right - 1; i >= left; i--)
			{
				res[down][i] = index;
				++index;
			}

			//左边
			if (down != up)
			for (int i = down - 1; i >= up + 1; i--)
			{
				res[i][left] = index;
				++index;
			}

			left++;
			right--;
			up++;
			down--;
		}
		return res;
	}
};

int main(void)
{
	Solution my_class;
	vector> res;

	res = my_class.generateMatrix(2);

	if (!res.empty())
	for (int i = 0; i < res.size(); i++)
	{
		for (int j = 0; j < res[i].size(); j++)
		{
			cout << res[i][j] << " ";
		}
		cout << endl;
	}
	
	system("pause");
	return 0;
}

 

你可能感兴趣的:(LeetCode-----第五十九题----- 螺旋矩阵 II)