栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

54. 螺旋矩阵【中等,模拟】

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

54. 螺旋矩阵【中等,模拟】

题目链接:54. 螺旋矩阵
进阶题目:59. 螺旋矩阵 II
相同题目:剑指 Offer 29. 顺时针打印矩阵,这里简单难度
两题会做一题,则另外一题就会做
我是先做了59再做54的,所以这题比较快

class Solution {
public:
	vector spiralOrder(vector>& matrix) {
		int maxNum = matrix.size() * matrix[0].size();
		int curNum = 0;
		int i = 0;
		int j = 0;
		vector v;
		vector> directions = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };  // 右下左上
		int directionIndex = 0;

		while (curNum < maxNum) {
			v.push_back(matrix[i][j]);
			curNum++;           //计数
			matrix[i][j] = 0;   //标记走过的

			//判断是否转向
			int next_i = i + directions[directionIndex][0];
			int next_j = j + directions[directionIndex][1];
			if (next_i < 0 || next_i >= matrix.size() || next_j < 0 || next_j >= matrix[0].size() || matrix[next_i][next_j] == 0) {
				directionIndex = (directionIndex + 1) % 4;  // 顺时针旋转至下一个方向
			}

			i = i + directions[directionIndex][0];
			j = j + directions[directionIndex][1];
		}

		return v;
	}
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/656204.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号