LeetCode OJ:Spiral Matrix(螺旋矩阵)
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问题,与前面一个问题比较像,代码如下。单独维护一个数组记录是否已经走过某个格子,注意边界条件的判断就可以了,代码如下:
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int>>& matrix) { 4 drt = vector<vector<int>>{{0,1},{1,0},{-1,0},{0,-1}}; //四个方向 5 mark = vector<vector<bool>>(100,vector<bool>(100,false)); 6 ret.clear(); 7 if(!matrix.size() || !matrix[0].size()) 8 return ret; 9 dfs(matrix, 0, 0, -1);//这里取-1是为了能从(0,0)开始。 10 return ret; 11 } 12 13 void dfs(vector<vector<int>> & matrix, int direct, int x, int y) 14 { 15 for(int i = 0; i < 4; ++i){ 16 int j = (direct + i) % 4; 17 int tx = x + drt[j][0]; 18 int ty = y + drt[j][1]; 19 if(tx >= 0 && tx < matrix.size() && 20 ty >= 0 && ty < matrix[0].size() && 21 mark[tx][ty] == false){ 22 mark[tx][ty] = true; 23 ret.push_back(matrix[tx][ty]); 24 dfs(matrix, j, tx, ty); 25 } 26 } 27 } 28 29 private: 30 vector<vector<int>> drt; 31 vector<vector<bool>> mark; 32 vector<int> ret; 33 };