【LeetCode】54. Spiral Matrix(C++)

地址:https://leetcode.com/problems/spiral-matrix/

题目:

Given a matrix of m x n m x n mxn elements ( m m m rows, n n n columns), return all elements of the matrix in spiral order.
Example 1:
在这里插入图片描述

Example 2:
在这里插入图片描述

理解:

按规则走一遍就可以了。

实现:

class Solution {
public:
	vector<int> spiralOrder(vector<vector<int>>& matrix) {
		vector<int> res;
        if(matrix.empty()) return res;
		int u = 0, d = matrix.size()-1, l = 0, r = matrix[0].size()-1;
		char direction = 'r';
		res.push_back(matrix[0][0]);
		int i = 0, j = 0;
		while (l<=r&&u<=d) {
			switch (direction) {
			case 'r':
				while (j < r) {
					res.push_back(matrix[i][j+1]);
					++j;
				}
				direction = 'd';
				u++;
				break;
			case 'd':
				while (i < d) {
					res.push_back(matrix[i+1][j]);
					++i;
				}
				direction = 'l';
				r--;
				break;
			case 'l':
				while (j > l) {
					res.push_back(matrix[i][j-1]);
					--j;
				}
				direction = 'u';
				d--;
				break;
			case 'u':
				while (i > u) {
					res.push_back(matrix[i-1][j]);
					--i;
				}
				direction = 'r';
				++l;
			}
		}
		return res;
	}
};

虽然写出来了,但是感觉思维有点混乱。
重新写一下吧。

实现2:

可以理解每次走最外圈的矩形。
四个顶点分别是 ( x 1 , y 1 ) (x_1,y_1) (x1,y1), ( x 1 , y 2 ) (x_1,y_2) (x1,y2), ( x 2 , y 1 ) (x_2,y_1) (x2,y1) ( x 2 , y 2 ) (x_2,y_2) (x2,y2)
注意到每次走完一条边,就把对应的坐标缩小了,因此需要多一次判断是否满足构成矩形的条件,不够就退出,说明已经遍历完了。这样的思路更清楚,而且避免了上面一直用ij来索引导致奇怪的赋值下标。
在这里插入图片描述

class Solution {
public:
	vector<int> spiralOrder(vector<vector<int>>& matrix) {
		if (matrix.empty()) return{};
		int x1 = 0, y1 = 0;
		int x2 = matrix.size() - 1, y2 = matrix[0].size() - 1;
		vector<int> res((x2 + 1)*(y2 + 1));
		int cnt = 0;
		while (x1<=x2&&y1<=y2) {
			for (int i = x1, j = y1; j <= y2; ++j) {
				res[cnt++] = matrix[i][j];
			}
			++x1;
			if (x1 > x2 || y1 > y2) break;
			for (int i = x1, j = y2; i <= x2; ++i) {
				res[cnt++] = matrix[i][j];
			}
			--y2;
			if (x1 > x2 || y1 > y2) break;
			for (int i = x2, j = y2; j >= y1; --j) {
				res[cnt++] = matrix[i][j];
			}
			--x2;
			if (x1 > x2 || y1 > y2) break;
			for (int i = x2, j = y1; i >= x1; --i) {
				res[cnt++] = matrix[i][j];
			}
			++y1;
		}
		return res;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值