【Leetcode】54. Spiral Matrix(模拟)

超、凢脫俗 2022-03-01 14:42 315阅读 0赞

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

  1. Input:
  2. [
  3. [ 1, 2, 3 ],
  4. [ 4, 5, 6 ],
  5. [ 7, 8, 9 ]
  6. ]
  7. Output: [1,2,3,6,9,8,7,4,5]

Example 2:

  1. Input:
  2. [
  3. [1, 2, 3, 4],
  4. [5, 6, 7, 8],
  5. [9,10,11,12]
  6. ]
  7. Output: [1,2,3,4,8,12,11,10,9,5,6,7]

题目大意:

题目要求我们依照顺时针方向(右,下,左,上),来遍历整个二维矩阵。将其按照一维数组输出。

解题思路:

我们只需要控制好方向即可,将判断是否更改前进方向的标准设置为:1、是否超出二维矩阵本身。2、收否已经被遍历过。

可以使用搜索,也可以直接用while循环。注意在判断是否已经被遍历过时,可以初始化另外一个辅助数组。

  1. class Solution {
  2. private:
  3. int g[4][2] = {
  4. {0,1},{1,0},{0, -1},{-1,0}};
  5. vector<int> ans;
  6. vector<vector<bool> > map;
  7. int n,m;
  8. int dir;
  9. void dfs(int x, int y, vector<vector<bool> > map, vector<vector<int> > matrix){
  10. if(ans.size()==m*n){
  11. return ;
  12. }
  13. int cor_x = x + g[dir][0];
  14. int cor_y = y + g[dir][1];
  15. if (valid(cor_x, cor_y, map) == false){
  16. dir = (dir+1)%4;
  17. cor_x = x + g[dir][0];
  18. cor_y = y + g[dir][1];
  19. }
  20. ans.push_back(matrix[cor_x][cor_y]);
  21. map[cor_x+1][cor_y+1] = true;
  22. dfs(cor_x, cor_y, map, matrix);
  23. if(ans.size()==m*n){
  24. return ;
  25. }
  26. }
  27. bool valid(int x, int y, vector<vector<bool> > map){
  28. if (x<n&&x>=0&&y>=0&&y<m&&map[x+1][y+1]==false){
  29. return true;
  30. }
  31. return false;
  32. }
  33. public:
  34. vector<int> spiralOrder(vector<vector<int> >& matrix) {
  35. if (matrix.size() == 0){
  36. return ans;
  37. }
  38. n = matrix.size();
  39. m = matrix[0].size();
  40. for(int i = 0; i<n+2;i++){
  41. vector<bool> v;
  42. for (int j = 0; j<m+2;j++){
  43. v.push_back(false);
  44. }
  45. map.push_back(v);
  46. }
  47. ans.push_back(matrix[0][0]);
  48. map[1][1] = true;
  49. dir = 0;
  50. dfs(0,0,map, matrix);
  51. return ans;
  52. }
  53. };

发表评论

表情:
评论列表 (有 0 条评论,315人围观)

还没有评论,来说两句吧...

相关阅读