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;
};

最新文章

  1. 338. Counting Bits
  2. 《foreach循环示例》
  3. Msp430概述
  4. 理解java Web项目中的路径问题
  5. T-SQL 控制流语句
  6. idea 15 搭建maven web项目
  7. css如何使背景图片水平居中
  8. JavaScript之面向对象学九(原型式继承和寄生式继承)
  9. DSP TMS320C6000基础学习(7)—— Bootloader与VectorTable
  10. C语言基础题
  11. iOS js oc相互调用(JavaScriptCore 下)
  12. 数位DP HDU - 2089 不要62
  13. 复旦大学2018--2019学年第一学期(18级)高等代数I期末考试第七大题解答
  14. 初识wxPython
  15. python小数据池,代码块知识
  16. kubernetes备份和恢复
  17. 如何解决SSH连接Linux超时自动断开?
  18. 10 python 封装----@property的用法
  19. webdriver屏幕截图(python)
  20. 一个可以自由存取的onedriver

热门文章

  1. PHP 安装memcache.so 和memcached.so
  2. android学习五---OpenCV for android环境搭建
  3. 如何实现关系表的级联删除(ON DELETE CASCADE的用法)
  4. iOS数据存储到本地的几种方法
  5. Codeforces Round #397 by Kaspersky Lab and Barcelona Bootcamp (Div. 1 + Div. 2 combined) A - Neverending competitions
  6. MapReduce概述
  7. javascript Date对象 之 获取时间
  8. Json日期格式 转化为 YYYY-MM-DD-hh-mm-ss
  9. C# 异步同步调用
  10. 正则表达式:Python3中的应用简介