Leetcode NO.59 Spiral Matrix II

来源:互联网 发布:淘宝助手与千牛 编辑:程序博客网 时间:2024/06/14 04:40

本题题目要求如下:

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 ]]
本题是道中等难度的题,对思维要求不高,想到了方法就必然能做出来。。别的好多题即使想到了也得费很多功夫实现。。。但是。。这道题我没有想到,我是不是太傻了。思考20分钟无果后,果断怒看讨论区。。

代码如下:

class Solution {public:    vector<vector<int> > generateMatrix(int n) {        vector<vector<int>> retVal(n, vector<int>(n, 0));/* first arg is the num of element, second is value */        int i = 0;        int j = 0;        int direction = 0;        for(int k = 1; k <= pow(n,2); ++k) {        retVal[i][j] = k;        /* next step: change the direction if necessary */        if (direction == 0) {        /* left to right */        ++j;        if (j == n || retVal[i][j] != 0) {        --j;        ++i;        direction = 1;        }        }        else if (direction == 1) {        /* top to bottom */        ++i;        if (i == n || retVal[i][j] != 0) {        --i;        --j;        direction = 2;        }        }        else if (direction == 2) {        /* right to left */        --j;        if (j < 0 || retVal[i][j] != 0) {        ++j;        --i;        direction = 3;        }        }        else if (direction == 3) {        /* bottom to top */        --i;        if (i < 0 || retVal[i][j] != 0) {        ++i;        ++j;        direction = 0;        }        }        }        return retVal;    }};
长度很长,但都是重复性代码,和心思想就是:

1,设定一个方向变量,

2,初始是从左向右,然后如果横坐标等于n,或者遇到了之前已经赋过值的元素,方向变为向下

3,如果纵坐标等于n,或者遇到之前赋过值的元素,方向改变为向左。

之后同理。。。

要记住这种思路!

0 0