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].
思路:将右,下,左,上连成环后,遍历,注意范围。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ans;
if (matrix.empty())
return ans;
int n = matrix.size(), m = matrix[0].size();
int vis[1000][1000];
memset(vis, 0, sizeof(vis));
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int dir = 0, x = 0, y = 0;
for (int i = 0; i < n*m; i++) {
ans.push_back(matrix[x][y]);
vis[x][y] = 1;
if (x+dx[dir] == n || x+dx[dir] < 0 ||
y+dy[dir] == m || y+dy[dir] < 0 ||
vis[x+dx[dir]][y+dy[dir]]) {
dir = (dir == 3) ? 0 : dir+1;
}
x += dx[dir];
y += dy[dir];
}
return ans;
}
};
原文:http://blog.csdn.net/u011345136/article/details/44239011