码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Spiral Matrix II

时间:2015-03-06 16:19:22      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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 <<",\t" << 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;
        }
};

 

[LeetCode] Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4318326.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!