leetcode || Spiral Matrix
来源:互联网 发布:淘宝售后退款不提醒 编辑:程序博客网 时间:2024/06/05 17:53
problem:
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]
.
题意:顺时针螺旋输出矩阵
thinking:
(1)首先想到方法是DFS,把外圈的数字输出之后,矩阵的行和列都缩减了2,递归调用。思路简单。
实现类似于:http://blog.csdn.net/hustyangju/article/details/44812157
(2)全局搜索,考虑用DFS。与方法一类似,只是DFS思路略有不同,这里参考:http://www.cnblogs.com/remlostime/archive/2012/11/18/2775708.html
一直关注他的实现,简洁高效,膜拜中
开一个数组用来保存,之前这个单元是否被使用过,并配合边界判断,DFS,最后得出结果。空间复杂度O(n*m),时间O(n*m)
code:
class Solution {private: int step[4][2]; vector<int> ret; bool canUse[100][100];public: void dfs(vector<vector<int> > &matrix, int direct, int x, int y) { for(int i = 0; i < 4; i++) { int j = (direct + i) % 4; int tx = x + step[j][0]; int ty = y + step[j][1]; if (0 <= tx && tx < matrix.size() && 0 <= ty && ty < matrix[0].size() && canUse[tx][ty]) { canUse[tx][ty] = false; ret.push_back(matrix[tx][ty]); dfs(matrix, j, tx, ty); } } } vector<int> spiralOrder(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function step[0][0] = 0; step[0][1] = 1; step[1][0] = 1; step[1][1] = 0; step[2][0] = 0; step[2][1] = -1; step[3][0] = -1; step[3][1] = 0; ret.clear(); memset(canUse, true, sizeof(canUse)); dfs(matrix, 0, 0, -1); return ret; }};
0 0
- [leetcode]Spiral Matrix&&Spiral Matrix II
- Leetcode:Spiral Matrix与Spiral Matrix II
- LeetCode | Spiral Matrix /Spiral Matrix II
- 【Leetcode】【python】Spiral Matrix/Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix
- [Leetcode] Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode] Spiral Matrix
- leetcode 80: Spiral Matrix
- [Leetcode] Spiral Matrix
- [LeetCode]Spiral Matrix
- [LeetCode]Spiral Matrix II
- RAC中的日志的目录结构
- linux 解压操作命令
- Struts2中带参数的结果集
- MVC中数据传递 ViewBag的使用
- 十六进制转八进制
- leetcode || Spiral Matrix
- hdu1160简单dp最长下降子序列
- Word怎么能有效转换成PDF格式
- 黑马程序员--java基础--网络编程(UDP和TCP)
- 由于检索用户的本地应用程序数据路径时出错,导致无法生成 SQL Server 的用户实例。解决方案
- 机器学习&数据挖掘笔记_16(常见面试之机器学习算法思想简单梳理)
- file文件复制
- CoreText实现图文混排
- Doxygen简介