zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    简述序列化与反序列化
    更新Kali源&&Docker vulhub 安装
    超级弱口令爆破工具&&hydra
    通达OA任意用户登录
    读书笔记——白帽子讲Web安全
    骑士CMS搭建与利用
    记一次DVWA的SQL注入测试
    网络基础
    C#类对象的事件定义
    [开源]FreeSCADA的通道数据与控件属性关联以及自动刷新机制研究
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4924611.html
Copyright © 2011-2022 走看看