这道编程问题和leetcode上的不太一样,具体代码实现操作的是奇数阶矩阵,从奇数阶矩阵的中心单元开始,自里向外螺旋形遍历矩阵的所有元素,遍历过程中用递增计数器标记经过的元素.以下代码中的run_order表示遍历方向遵循的循环次序,譬如代码中的vector<size_t> run_order = { 3, 0, 2, 1 };表示遍历时先向上走,再向左走,再向下走,最后向右走,随后不断重复这一方向循环,直到矩阵所有元素均被访问为止.注意以下代码并不适用于一阶矩阵
C++代码:
cpp
#include <iostream>
#include <vector>
#include <utility>
using std::vector;
using std::pair;
struct Coord
{
long long x;
long long y;
Coord(size_t x, size_t y) :x(x), y(y) {}
Coord operator+(const Coord& c)
{
return Coord(x + c.x, y + c.y);
}
Coord operator-()
{
return Coord(-x, -y);
}
};
int main()
{
size_t N = 3; //N为奇数,N>=3,N= 1的情形是平凡的,不予考虑
vector<vector<size_t>> matrix(N, vector<size_t>(N, 0));
//左,右,下,上
vector<Coord> offset = { Coord(0, -1), Coord(0, 1), Coord(1, 0), Coord(-1, 0) };
vector<size_t> run_order = { 3, 0, 2, 1 }; //方向,0-左,1-右,2-下,3-上
size_t pre_d = 3;
size_t d = 0;
long long x = N / 2 + 1;
long long y = N / 2 + 1;
Coord c(x, y);
size_t count = 1;
matrix[c.x - 1][c.y - 1] = count++;
c = c + offset[run_order[d]];
while (true)
{
matrix[c.x - 1][c.y - 1] = count++;
Coord temp_c = c + ( - offset[run_order[pre_d]]);
if (matrix[temp_c.x - 1][temp_c.y - 1] != 0)
{
c = c + offset[run_order[d]];
if (c.x == 0 || c.x == N + 1 || c.y == 0 || c.y == N + 1)
{
break;
}
}
else
{
c = temp_c;
pre_d = d;
d = (d + 1) % 4;
}
}
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}