【数组】螺旋矩阵II

题目链接:螺旋矩阵 II
关键点:
【1】正整数
【2】顺时针排列
思路:先创建一个nxn的矩阵,并且将矩阵中每个元素都置为0,从矩阵的左上角第一个位置,先向右填充整数,当遇到边缘,就调整方向,向下填充,遇到边缘,再次调整方向向左填充,如此,当遇到某元素的值为nxn,说明填充完毕。
在这里插入图片描述

#include <iostream>
#include <vector>

class Solution
{
public:
	std::vector<std::vector<int>> generateMatrix(int n)
	{
		// 创建一个nxn的矩阵,并将每个元素初始化为0
		std::vector<std::vector<int>> result(n, std::vector<int>(n, 0));
		int row = 0; // 行坐标
		int col = 0; // 列坐标
		result[row][col] = 1; // 首个元素
		while (result[row][col] != n * n) // 当前元素的值是否为nxn,及矩阵中心位置元素的值
		{
			while (col + 1 < n && 0 == result[row][col+1]) // 向右填充
			{
				result[row][col + 1] = result[row][col] + 1;
				col++; // 横坐标不变,列坐标++
			}

			while (row + 1 < n && 0 == result[row+1][col]) // 向下填充
			{
				result[row + 1][col] = result[row][col] + 1;
				row++; // 列坐标不变,横坐标++
			}

			while (col - 1 >= 0 && 0 == result[row][col-1])// 向左填充
			{
				result[row][col - 1] = result[row][col] + 1;
				col--; // 横坐标不变,列坐标--
			}

			while (row - 1 >= 0 && 0 == result[row - 1][col])// 向上填充
			{
				result[row - 1][col] = result[row][col] + 1;
				row--; // 列坐标不变,横坐标--
			}
		}
		return result;
	}
};


int main()
{

	Solution s;
	std::vector<std::vector<int>> vecMatrix = s.generateMatrix(3);
	return 0;
}

版权声明:本文为weixin_43669712原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。