59. Spiral Matrix II

来源:互联网 发布:c语言产生0 1的随机数 编辑:程序博客网 时间:2024/06/08 09:09

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 ]

]

解答:class Solution {public:    vector<vector<int>> generateMatrix(int n) {         vector<vector<int> > matrix(n,vector<int>(n,0));            if(n <= 0){                return matrix;            }//if            int count = n * n;            int index = 1;            int x = 0,y = -1;            while(index <= count){                // right                ++y;                while(y < n && matrix[x][y] == 0){                    matrix[x][y++] = index;                    ++index;                }//while                --y;                // down                ++x;                while(x < n && matrix[x][y] == 0){                    matrix[x++][y] = index;                    ++index;                }//while                --x;                // left                --y;                while(y >= 0 && matrix[x][y] == 0){                    matrix[x][y--] = index;                    ++index;                }//while                ++y;                // up                --x;                while(x >= 0 && matrix[x][y] == 0){                    matrix[x--][y] = index;                    ++index;                }//while                ++x;            }//while            return matrix;    }};

0 0
原创粉丝点击