Leetcode NO.59 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 ]
]
本题是道中等难度的题,对思维要求不高,想到了方法就必然能做出来。。别的好多题即使想到了也得费很多功夫实现。。。但是。。这道题我没有想到,我是不是太傻了。思考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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值