LeetCode Spiral Matrix

本文分享了一道高德笔试题目及解答过程,讨论了在遍历矩阵时如何正确处理边界条件,避免仅检查横排或竖排导致的问题,并提供了一个C++实现的示例代码。

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

记忆清晰呀,高德笔试题,可惜第一次还是提交失败,考虑不周到所致。就是在while里不能只判断横排或者竖排, 必须横竖都判断。

// LeetCode_MaximumSubarray.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

int maxSubArray(int A[], int n) {
	int curmax = A[0];
	int max = curmax;
	for (int i=1;i<n;i++)
	{
		if (curmax + A[i]>A[i])
			curmax = curmax + A[i];
		else
			curmax = A[i];
		if (curmax>max)
		{
			max = curmax;
		}
	}
	return max;
}

vector<int> spiralOrder(vector<vector<int> > &matrix) {
	vector<int> ret;
	int lenrows = matrix.size();
	if (lenrows==0)
	{
		return ret;
	}
	int lencolumns = matrix[0].size();
	int left=0,up = 0,down = lenrows-1 , right= lencolumns-1;
	int i,j;
	while(left<=right&&up<=down)
	{
		i = up;
		j = left;
		while(i>=up&&i<=down&&j>=left&&j<=right)
		{
			ret.push_back(matrix[i][j]);
			j++;
		}
		up++;
		i = up;
		j = right;
		while(i>=up&&i<=down&&j>=left&&j<=right)
		{
			ret.push_back(matrix[i][j]);
			i++;
		}
		right--;
		i = down;
		j =right;
		while(i>=up&&i<=down&&j>=left&&j<=right)
		{
			ret.push_back(matrix[i][j]);
			j--;
		}
		down--;
		i = down;
		j = left;
		while(i>=up&&i<=down&&j>=left&&j<=right)
		{
			ret.push_back(matrix[i][j]);
			i--;
		}
		left++;
	}
	return ret;
}

int _tmain(int argc, _TCHAR* argv[])
{
	//int arr[9]={-2,1,-3,4,-1,2,1,-5,4};
	//cout<<maxSubArray(arr,9)<<endl;
	vector<int> temp;
	vector<vector<int> >matrix;
	temp.push_back(1);
	//matrix.push_back(temp);
	//temp.clear();
	/*temp.push_back(2);
	temp.push_back(3);
	
	temp.push_back(4);
	temp.push_back(5);
	temp.push_back(6);
	matrix.push_back(temp);
	temp.clear();
	temp.push_back(7);
	temp.push_back(8);*/
	temp.push_back(9);
	matrix.push_back(temp);
	temp.clear();
	//matrix.clear();
	temp = spiralOrder(matrix);
	for (int i=0;i<temp.size();i++)
	{
		cout<<temp[i]<<" ";
	}
	cout<<endl;
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值