LeetCode OJ:Spiral Matrix(螺旋矩阵)
2024-10-21 11:50:14
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]
.
典型的dfs问题,与前面一个问题比较像,代码如下。单独维护一个数组记录是否已经走过某个格子,注意边界条件的判断就可以了,代码如下:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
drt = vector<vector<int>>{{,},{,},{-,},{,-}}; //四个方向
mark = vector<vector<bool>>(,vector<bool>(,false));
ret.clear();
if(!matrix.size() || !matrix[].size())
return ret;
dfs(matrix, , , -);//这里取-1是为了能从(0,0)开始。
return ret;
} void dfs(vector<vector<int>> & matrix, int direct, int x, int y)
{
for(int i = ; i < ; ++i){
int j = (direct + i) % ;
int tx = x + drt[j][];
int ty = y + drt[j][];
if(tx >= && tx < matrix.size() &&
ty >= && ty < matrix[].size() &&
mark[tx][ty] == false){
mark[tx][ty] = true;
ret.push_back(matrix[tx][ty]);
dfs(matrix, j, tx, ty);
}
}
} private:
vector<vector<int>> drt;
vector<vector<bool>> mark;
vector<int> ret;
};
最新文章
- 338. Counting Bits
- 《foreach循环示例》
- Msp430概述
- 理解java Web项目中的路径问题
- T-SQL 控制流语句
- idea 15 搭建maven web项目
- css如何使背景图片水平居中
- JavaScript之面向对象学九(原型式继承和寄生式继承)
- DSP TMS320C6000基础学习(7)—— Bootloader与VectorTable
- C语言基础题
- iOS js oc相互调用(JavaScriptCore 下)
- 数位DP HDU - 2089 不要62
- 复旦大学2018--2019学年第一学期(18级)高等代数I期末考试第七大题解答
- 初识wxPython
- python小数据池,代码块知识
- kubernetes备份和恢复
- 如何解决SSH连接Linux超时自动断开?
- 10 python 封装----@property的用法
- webdriver屏幕截图(python)
- 一个可以自由存取的onedriver
热门文章
- PHP 安装memcache.so 和memcached.so
- android学习五---OpenCV for android环境搭建
- 如何实现关系表的级联删除(ON DELETE CASCADE的用法)
- iOS数据存储到本地的几种方法
- Codeforces Round #397 by Kaspersky Lab and Barcelona Bootcamp (Div. 1 + Div. 2 combined) A - Neverending competitions
- MapReduce概述
- javascript Date对象 之 获取时间
- Json日期格式 转化为 YYYY-MM-DD-hh-mm-ss
- C# 异步同步调用
- 正则表达式:Python3中的应用简介