• LeetCode OJ:Spiral MatrixII(螺旋矩阵II)


    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    For example,
    Given n = 3,

    You should return the following matrix:

    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]

    依旧是dfs问题,代码如下所示:

     1 class Solution {
     2 public:
     3     vector<vector<int>> generateMatrix(int n) {
     4         vector<vector<int>>ret(n, vector<int>(n, 0));
     5         vector<vector<bool>>mark(n, vector<bool>(n,false));
     6         if(!n) return ret;
     7         dfs(ret, mark, 0, -1, n, 0, 1);
     8         return ret;
     9     }
    10 
    11     void dfs(vector<vector<int>> & ret, vector<vector<bool>> & mark, int i, int j, int n, int curr, int currVal)
    12     {
    13         for(int k = 0; k < 4; ++k){
    14             int dirct = (curr + k) % 4;
    15             int ii = i + drct[dirct][0];
    16             int jj = j + drct[dirct][1];
    17             if(ii >= 0 && ii < n && 
    18                 jj >= 0 && jj < n &&
    19                 mark[ii][jj] == false){
    20                 mark[ii][jj] = true;
    21                 ret[ii][jj] = currVal;
    22                 dfs(ret, mark, ii, jj, n, dirct, currVal + 1);
    23             }
    24 
    25         }
    26     }   
    27 
    28 private:
    29     vector<vector<int>>drct = {{0,1},{1,0},{0,-1},{-1,0}};
    30 };

    代码写的比较乱,凑合着看哈哈 

  • 相关阅读:
    Linux下的lds链接脚本详解
    STM32启动过程解读与跟踪验证
    STM32的启动过程分析
    STM32启动过程--启动文件--分析
    STM32之中断
    STM32F4XX启动文件分析
    Synergy CORTEX M 启动流程
    AT 指令和常见错误码
    Tomcat部署时war和war exploded区别
    C++虚函数表解析***
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4932733.html
Copyright © 2020-2023  润新知