59.Spiral Matrix II

思路
  • 类似Spiral Matrix,直接模拟
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n,vector<int>(n));
        int rowbegin = 0, rowend = n-1;
        int colbegin = 0, colend = n-1;
        int k = 1;
        while(rowbegin <= rowend && colbegin <= colend){
            for(int i = colbegin; i <= colend; i++){
                res[rowbegin][i] = k++;
            }
            rowbegin++;
            for(int i = rowbegin; i <= rowend; i++){
                res[i][colend] = k++;
            }
            colend--;
            if(rowend >= rowbegin){
                for(int i = colend; i >= colbegin; i--){
                    res[rowend][i] = k++;
                }
                rowend--;
            }
            if(colbegin <= colend){
                for(int i = rowend; i >= rowbegin; i--){
                    res[i][colbegin] = k++;
                }
                colbegin++;
            }
        }
        return res;
    }
};
  • dfs:等做几道dfs后再来实现
posted @ 2017-06-09 12:02  UniMilky  阅读(119)  评论(0编辑  收藏  举报