54. 螺旋矩阵
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
解析:
先向右走,只要没有走到边界就不改变方向,之后遍历四个方向看看哪个能走即可
走过的路标记为一个不可访问的数
class Solution { public: int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int n, m; void dfs(vector<int>& ret, vector<vector<int> >& matrix, int k, int x, int y) { ret.push_back(matrix[x][y]); matrix[x][y] = -101; int tx = x + dir[k][0]; int ty = y + dir[k][1]; if(tx >= n || tx < 0 || ty >= m || ty < 0 || matrix[tx][ty] < -100) { int temp = k; for(int i = 0; i < 4; i++) { tx = x + dir[i][0]; ty = y + dir[i][1]; if(tx >= n || tx < 0 || ty >= m || ty < 0 || matrix[tx][ty] < -100) continue; k = i; break; } if(k != temp) dfs(ret, matrix, k, tx, ty); } else { dfs(ret, matrix, k, tx, ty); } } vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> ret; n = matrix.size(); m = matrix[0].size(); dfs(ret, matrix, 3, 0, 0); return ret; } };
标签:matrix,tx,ty,int,54,螺旋,矩阵,ret,vector From: https://www.cnblogs.com/WTSRUVF/p/16603385.html