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)首先想到的一个方法是递归法,把外圈的数字输出之后,矩阵的行和列都缩减了2,递归调用。思路简单,实现也不难,不再啰嗦
(2)又是全局搜索,可以考虑用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;
}
};原文地址:http://blog.csdn.net/hustyangju/article/details/44803443