spiral matrix

本文详细阐述了如何使用迭代和边界更新策略实现矩阵元素的螺旋遍历过程,包括两种方法:利用动态规划构建布尔表格遍历和通过方向变化依次遍历矩阵的四个边缘。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].


弄了一晚上就这么一个题。。。把自己弄晕了。。。两种方法,第一种用类似dp做一个bool table 来遍历。第二种就是 向右,向下,向左,向上。 其中向左和向上的时候检查是不是当前行列已经被打印,如果有,终止。


#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
	vector<int> spiralOrder(vector<vector<int> > &matrix) {
		vector<int> res;
		if (matrix.empty()||matrix[0].empty())
			return res;
		int x0, x1, y0, y1,i;
		x0=0; y0=0;
		x1=matrix.size()-1;y1=matrix[0].size()-1;

		while(x0<=x1 && y0<=y1){
			for (i=y0; i<=y1; i++)
				res.push_back(matrix[x0][i]);
			x0++;
			for (i=x0;i<=x1; i++)
				res.push_back(matrix[i][y1]);
			y1--;
			if (x0>x1)	break;
			for(i=y1;i>=y0; i--)
				res.push_back(matrix[x1][i]);
			x1--;
			if(y0>y1) break;
			for(i=x1;i>=x0; i--)
				res.push_back(matrix[i][y0]);
			y0++;
		}
		return res;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值