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 ]
]

思路:

与上一题一样的思路,上次是取数,这次是赋值。

定义一个count变量即可。

四条线路法,定义up,right,down,left四个变量,先走最上面,再走最右边,再走最下面,再走最左边,条件结束标志为左等于右,上等于下。

代码:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int> > matrix(n,vector<int>(n,0));
        //vector<vector<bool> >dp(m+1,vector<bool>(n+1,false));
        //int matrix[n][n];
        vector<vector<int>> result;
        if(n==0){
            return result;
        }
        
        int left=0,right=n-1;
        int up=0,down=n-1;
        int count=0;
        
        while(up<=down&&left<=right){
            for(int i=left;i<=right;i++){
                matrix[up][i]=++count;
                //res.push_back(matrix[up][i]);
                //matrix[up].push_back(++count);
            }
            
            for(int i=up+1;i<=down;i++){
                matrix[i][right]=++count;
                //res.push_back(matrix[i][right]);
            }
            
            if(up==down||left==right){    
                break;
            }
            
            for(int i=right-1;i>=left;i--){
                matrix[down][i]=++count;
                //res.push_back(matrix[down][i]);
            }
            
            for(int i=down-1;i>=up+1;i--){
                matrix[i][left]=++count;
                //res.push_back(matrix[i][left]);
            }
            up++;
            right--;
            down--;
            left++;
        }
        
        return matrix;
        
    }
};


posted @ 2015-10-25 09:21  JSRGFJZ6  阅读(105)  评论(0编辑  收藏  举报