简单的实现螺旋矩阵

16 15 14 13 

 5   4    3  12

 6   1    2  11

 7   8    9  10

const std::vector<std::vector<int>>/*&*/ CAlgorithm::screwMatrix(const int& width, const int&height )
{
	int differ = width - height;
	if (!(differ == 0 || differ == 1) || width + height < 2)
	{
		std::vector<std::vector<int>> buff;
		return buff;
	}


	std::vector<int> buff1(width,0);
	/*static*/ std::vector<std::vector<int>> buff0(height,buff1);

	int num = 1, start = width / 2 - 1, max = width * height;
	
	int j, count, x, y;

	for (int i = 2; i <= width + 1; i += 2)
	{
		j = 1;count = 1;
		//第一次取最里面的2X2的矩阵左上角点为初始点,之后每次把初始点斜向上移一格
		if (width <= 2)
		{
			if (height == 1)
			{
				x = -1;
				y = 0;
			}
			else 
			{
				x = y = 0;
			}
		}
		else
		{
			if (2 == i)
			{
				if (width % 2 == 0)
				{
					if (height % 2 == 0)
					{
						x = start;
						y = x;
					}
					else
					{
						x = start - 1;
						y = start;
					}
				}
				else
				{
					x = start;
					y = start +1;
				}
			}
			else
			{
				x -= 1;
				y -= 1;
			}
		}
		

		while (j < i)
		{
			switch(count)
			{
			case 1: ++x;break;
			case 2: ++y;break;
			case 3: --x;break;
			case 4: --y;break;
			}
			buff0[x][y] = num++;
			if (num > max)
			{
				break;
			}
			j++;
			if (j >= i && count < 4)
			{
				count++;
				j = 1;
			}
		}
	}

	for (int i = 0; i < height; i++)
		for(int j = 0; j < width; j++)
	{
		int temp = buff0[i][j];
		if(temp < 10)
			std::cout<<" "<<temp<<" ";
		else
			std::cout<<temp<<" ";
		if(j == width - 1)
			std::cout<<std::endl;
	}
	
	return buff0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值