• [LeetCode] Spiral Matrix 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 ]
    ]
    
    Hide Tags
     Array
     

    思路:在Spiral Matrix的基础上进行修改,还是dfs

    class Solution {
        enum direct{RIGHT = 0, DOWN, LEFT, UP};
        vector<int> m_res;
        vector<vector<int> > m_matrix;
        vector<vector<bool> > m_valid;
        int m_cnt;
        public:
            void dfs(int i, int j, enum direct d)  
            {   
                int row = m_matrix.size();
                int col = m_matrix[0].size();
    
                //cout << i <<",	" << j << endl;
                m_cnt++;
                m_matrix[i][j] = m_cnt;
                m_valid[i][j] = false;
    
                if(d == RIGHT)
                {
                    if( j <= col-2 && m_valid[i][j+1])
                        dfs(i, j+1, RIGHT);
                    else if(i <= row-2 && m_valid[i+1][j])
                        dfs(i+1, j, DOWN);
                }
                else if(d == DOWN)
                {
                    if(i <= row-2 && m_valid[i+1][j])
                        dfs(i+1, j, DOWN);
                    else if(j >= 1 && m_valid[i][j-1])
                        dfs(i, j-1, LEFT);
                }
                else if(d == LEFT)
                {
                    if(j >= 1 && m_valid[i][j-1] )
                        dfs(i, j-1, LEFT);
                    else if(i >= 1 && m_valid[i-1][j])
                        dfs(i-1, j, UP);
                }
                else if(d == UP)
                {
                    if(i >= 1 && m_valid[i-1][j])
                        dfs(i-1, j, UP);
                    else if(j <= col-1 && m_valid[i][j+1])
                        dfs(i, j+1, RIGHT );
                }
            }
    public:
            vector<vector<int> > generateMatrix(int n)
            {
                if(n == 0)
                    return m_matrix;
    
                // construct the matrix
                vector<int> row(n, 0);
                m_matrix.resize(n, row);
                //for(int i = 0; i < n; i++)
                //    m_matrix.push_back(row);
    
                vector<bool> valid(n, true);
                m_valid.resize(n, valid);
                //for(int i = 0; i < n; i++)
                //    m_valid.push_back(valid);
    
                m_cnt = 0;
    
                dfs(0, 0, RIGHT);
    
                return m_matrix;
            }
    };
  • 相关阅读:
    C# 调用cmd执行指令
    如何发布 silverlight wcf 简单易学
    C#读取特定目录下的所有文件
    用批处理bat一次安装所有的系统更新补丁
    动态创建datagrid序号
    学习DIV+CSS一个最简单的布局一行三列DIV代码!
    highslide图片查看特效
    相册程序mageVue
    让Apache支持ASP.NET
    ASP.NET四种页面导航方式之比较与选择
  • 原文地址:https://www.cnblogs.com/diegodu/p/4318326.html
Copyright © 2020-2023  润新知