螺旋矩阵

1.生成矩阵

class Solution {
public:
	vector<vector<int> >  creatMatrix(int n) {
		vector<vector<int> > mat(n, vector<int>(n, 0));
		int val = 1;
		if (n <= 0)
			return mat;
		if (n == 1)
			return { {1} };
		int right = n - 1;
		int left = 0;
		int top = 0;
		int bottom = n - 1;

		while (top <= bottom && left <= right) {
			//左到右
			for (int i = left; i <= right; i++)
				mat[top][i] = val++;
			//上到下
			for (int i = top + 1; i <= bottom; i++)
				mat[i][right] = val++;
			//右到左
			if (top != bottom) {
				for (int i = right - 1; i >= left; i--)
					mat[bottom][i] = val++;
			}

			//下到上
			if (left != right) {
				for (int i = bottom - 1; i > top; i--)
					mat[i][left] = val++;
			}
			right--; left++; top++; bottom--;
		}
		return mat;
	}
};

2.打印矩阵

class Solution {
public:
	vector<int> creatMatrix(vector<vector<int> > mat) {
	    int m = mat.sise();
        int n = mat[0].size();
        vector<int> res;
		
		if (n <= 0)
			return res;
		int right = n - 1;
		int left = 0;
		int top = 0;
		int bottom = m - 1;

		while (top <= bottom && left <= right) {
			//左到右
			for (int i = left; i <= right; i++)
				res.push_back(mat[top][i]);
			//上到下
			for (int i = top + 1; i <= bottom; i++)
				res.push_back(mat[i][right);
			//右到左
			if (top != bottom) {
				for (int i = right - 1; i >= left; i--)
					res.push_back(mat[bottom][i]);
			}

			//下到上
			if (left != right) {
				for (int i = bottom - 1; i > top; i--)
					res.push_back(mat[i][left]);
			}
			right--; left++; top++; bottom--;
		}
		return res;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值