力扣经典题目:螺旋矩阵

问题详情

给一个正整数n,生成一个n行n列的二维矩阵,并将1到n^2所有元素按顺时针顺序写入矩阵。

比如,对于正整数3,布置顺序如下图:
在这里插入图片描述

返回以下矩阵:
{
{1,2,3},
{8,9,4},
{7,6,5},
}

解题思路

根据问题详情中的信息,可以得到以下结论:

  1. 1到n^2中所有数字都会被写入矩阵中;
  2. 写入过程从左上角角点开始,一直往一个方向往前一格写入下一个数字,直到越界或者下一格已经写入过数字;
  3. 碰到越界或者下一格已经写入数字的情况,写入方向需要调整,按顺时针方向调整(右、下、左、上、右)。
  4. 所有数字都写完时,结束。

根据上面结论,可以得到实现步骤如下:

  1. 初始化n行n列的结果矩阵,元素都为0;
  2. 定义方向矩阵和初始方向,定义初始布置位置行号列号;
  3. 遍历从1到n^2各个数字;
  4. 往当前位置写入数字;
  5. 根据下一格是否行越界、列越界、数值大于0,判别是否需要调整搜索方向;
  6. 根据搜索方向,计算下一次的布置位置;
  7. 重复4~6过程直到结束;
  8. 输出结果矩阵;

代码实现

输入条件设定为n=5,根据解题思路编写代码。

vector<vector<int>> generateMatrix(int n)
{
	vector<vector<int>> matrix(n, vector<int>(n, 0));
	int totalCount = n * n;
	vector<int> dirs = { 0,1,0,-1,0 };
	int dirIndex = 0;
	int rowIndex = 0;
	int colIndex = 0;
	for (int i = 0; i < totalCount; ++i)
	{
		matrix[rowIndex][colIndex] = i + 1;
		int nextRowIndex = rowIndex + dirs[dirIndex];
		int nextColIndex = colIndex + dirs[dirIndex + 1];
		if (nextRowIndex < 0 || nextRowIndex >= n || nextColIndex < 0 || nextColIndex >= n || matrix[nextRowIndex][nextColIndex] != 0)
			dirIndex = (dirIndex + 1) % 4;
		rowIndex = rowIndex + dirs[dirIndex];
		colIndex = colIndex + dirs[dirIndex + 1];
	}
	return matrix;
}

int main()
{
	vector<vector<int>> result = generateMatrix(5);
	for (int i = 0; i < result.size(); ++i)
	{
		string str;
		for (int j = 0; j < result[i].size(); ++j)
		{
			str = str + " " + to_string(result[i][j]);
		}
		str = str.substr(1);
		std::cout << str << endl;
	}
}

运行结果

n=5时,预期的结果矩阵如下:
{
{1 , 2 , 3 , 4 , 5},
{16,17,18,19,6},
{15,24,25,20,7},
{14,23,22,21,8},
{13,12,11,10,9},
}

代码运行结果如下图:
在这里插入图片描述
对比可知,运行结果符合预期。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

饮血太岁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值