螺旋形遍历奇数阶矩阵

这道编程问题和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;
}
相关推荐
2501_9269783313 小时前
提示工程的实战报告(二):模型的失败模式与边界行为
人工智能·深度学习·算法
小小晓.13 小时前
C++记:函数
开发语言·c++·算法
casual~13 小时前
模逆元计算方法详解:扩展欧几里得算法与费马小定理
学习·算法·逆元
脚踏实地皮皮晨14 小时前
002002002_DepandencyObject类2
开发语言·windows·算法·c#·visual studio
charlie11451419114 小时前
Cinux —— 给物理内存建账本:bitmap 物理内存管理器
开发语言·c++·操作系统·开源项目
冻柠檬飞冰走茶15 小时前
PTA基础编程题目集 7-27 冒泡法排序(C语言实现)
c语言·开发语言·数据结构·算法
大鱼>16 小时前
因子挖掘+回测+RL交易:量化金融完整系统
人工智能·深度学习·算法·金融
2301_7779983417 小时前
Linux线程同步与互斥(三):信号量与环形队列实现生产者消费者模型
linux·c语言·c++
啦啦啦啦啦zzzz17 小时前
设计模式:单例模式和工厂模式
c++·单例模式·设计模式·工厂模式
Henry Zhu12317 小时前
C++ 动态多态详解
c++