问题详情
给一个正整数n,生成一个n行n列的二维矩阵,并将1到n^2所有元素按顺时针顺序写入矩阵。
比如,对于正整数3,布置顺序如下图:
返回以下矩阵:
{
{1,2,3},
{8,9,4},
{7,6,5},
}
解题思路
根据问题详情中的信息,可以得到以下结论:
- 1到n^2中所有数字都会被写入矩阵中;
- 写入过程从左上角角点开始,一直往一个方向往前一格写入下一个数字,直到越界或者下一格已经写入过数字;
- 碰到越界或者下一格已经写入数字的情况,写入方向需要调整,按顺时针方向调整(右、下、左、上、右)。
- 所有数字都写完时,结束。
根据上面结论,可以得到实现步骤如下:
- 初始化n行n列的结果矩阵,元素都为0;
- 定义方向矩阵和初始方向,定义初始布置位置行号列号;
- 遍历从1到n^2各个数字;
- 往当前位置写入数字;
- 根据下一格是否行越界、列越界、数值大于0,判别是否需要调整搜索方向;
- 根据搜索方向,计算下一次的布置位置;
- 重复4~6过程直到结束;
- 输出结果矩阵;
代码实现
输入条件设定为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},
}
代码运行结果如下图:
对比可知,运行结果符合预期。