Spiral Matrix

本文介绍了一种使用四个for循环实现的螺旋遍历矩阵的方法,并解决了LeetCode上出现的runtime error问题。通过调整变量声明的位置,成功避免了潜在的栈溢出问题。

摘要生成于 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].


1.vector<vector <int> > matrix如何求矩阵的m和n

m = matrix.size();

n = matrix[0].size();

接下来就可以先从左到右,从上到下,从右到左,从下到上了。

4个for循环搞掂。

2.leetcode为什么总是报runtime error?

据说是因为数组越界,除0,爆栈,访问空地址

写这个程序的时候方法和别人的一样,我用了4个for循环,但是runtime error并不是因为时间复杂度过大,时间复杂度太大报的是timeout之类的

在电脑上各种用例反复测试就是没问题,那到底是为什么,因为我定义的变量太多了,我把定义的那些变量删去后就accept了。

前后对比如下:仅仅是因为前面多了个求m和n的取值,难道这是爆栈

class Solution{
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) 
    {
        vector<int> result;
		int i = 0,j = 0;
		int m = matrix.size();
		int n = matrix[0].size();
		if(m == 0)
			return vector<int>();
		int startx = 0;
		int endx = matrix.size() - 1;
		int starty = 0;
		int endy = matrix[0].size() - 1;
		while(startx <= endx && starty <= endy)
		{
			for(j = starty; j <= endy; ++j)
			{
				result.push_back(matrix[startx][j]);
			}
			startx++;
			for(i = startx; i <= endx; ++i)
			{
				result.push_back(matrix[i][endy]);
			}
			endy--;
			if(startx <= endx)
			{
				for(j = endy; j >= starty; --j)
					result.push_back(matrix[endx][j]);
			}
			endx--;
			if(starty <= endy)
			{
				for(i = endx; i >= startx; --i)
				{
					result.push_back(matrix[i][starty]);
				}
				starty++;
			}
		}
		return result;
    }
};


class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) 
    {
        vector<int> result;
		int i = 0,j = 0;
		if(matrix.size() == 0)
			return vector<int>();
		int startx = 0;
		int endx = matrix.size() - 1;
		int starty = 0;
		int endy = matrix[0].size() - 1;
		while(startx <= endx && starty <= endy)
		{
			for(j = starty; j <= endy; ++j)
			{
				result.push_back(matrix[startx][j]);
			}
			startx++;
			for(i = startx; i <= endx; ++i)
			{
				result.push_back(matrix[i][endy]);
			}
			endy--;
			if(startx <= endx)
			{
				for(j = endy; j >= starty; --j)
					result.push_back(matrix[endx][j]);
			}
			endx--;
			if(starty <= endy)
			{
				for(i = endx; i >= startx; --i)
				{
					result.push_back(matrix[i][starty]);
				}
				starty++;
			}
		}
		return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值