leetcode 螺旋矩阵

59

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例 1:
1 2 3
8 9 4
7 6 5

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:

输入:n = 1
输出:[[1]]

思路:
要控制每一条边的边界取值,取左闭右开,模拟顺时针画矩阵的过程
在这里插入图片描述

class Solution
{
public:
	vector<vector<int>> generateMatrix(int n){
		vector<vector<int>>res(n,vector<int>(n,0)); //定义一个二维数组
		int mid=n/2; //中间位置
		int startx=0,starty=0; //每一圈的起始位置
		int i,j;
		int count=1;
		int offset=n/2;
		int loop=n/2; //每一圈循环的次数,就是一共有多少圈
		while(loop--)
		{
			i=startx;
			j=starty;
			for(j=starty;j<starty+n-offset;j++)
			{
				res[stratx][j]=count++;
			}
			for(i=startx;i<startx+n-offset;i++)
			{
				res[i][j]=count++;
			}
			for(;j>starty;j--)
			{
				res[i][j]=count++;
			}
			for(;i>startx;i--)
			{
				res[i][j]=count++;
			}
			startx++;
			starty++; //到下一圈要到新的起始位置比如(1,1)
			offset+=2;
		}
		if(n%2!=0)
		{
			res[mid][mid]=-count; //给最中间的值赋值
		}
		return res;
	}
};

顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

思路:
很显然需要一个一维数组来存储最终的结果
这个可以也是参照上图的例子来从最外层逐步求解
遍历顺序:
上:top,left-----------top,right
右:top+1,right------bottom,right
下:bottom,right-1–bottom,left+1
左:bottom,left----top+1,left

class Solution
{
	publc:
		vector<int> spiralOrder(vector<vector<int>> &Matrix)
		{
			vector<int> order;
			int rows=matrix.size();
			int columns=matrix[0].size();
			int top=0,right=columns-1,left=0,bottom=rows-1;
			while(left<=right && top<=bottom)
			{
				for(int column=left;column<=right;column++)
				{
					order.push_back(matrix[top][column]);
				}
				for(int row=top+1;row<=bottom;row++)
				{
					order.push_back(matrix[row][right]);
				}
				if(left<right && top< bottom)
				{
					for(int column=right-1;column>left;column--)
					{
						order.push_back(matrix[bottom][column]);
					}
					for(int row=bottom;row>top;row--)
					{
						order.push_back(matrix[row][left]);
					}
				}
				top++;
				left++;
				right--;
				bottom--;
			}
			return order;
		}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值