作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/spiral-matrix-ii/description/

题目描述

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

题目大意

顺时针由内向内螺旋状把1~n^2这些数字生成二维矩阵。

解题方法

明显是54. Spiral Matrix的翻版,54题让我们打印,这个题让我们生成。因此其实是一样的套路,都是同样的方式进行遍历。

这个题由于没有给matrix,所以自己生成一个正方形的矩阵,然后把54题的读取matrix的值改为给matrix当前位置填写值即可。

维护四个边界和运动方向

螺旋填充,一定会在遍历的时候更改方向。在什么时候更改方向呢?在最外圈运动的时候是到达边界的时候。但是当移动到Example 1中4的位置时,要向右移动(而不是向上),那么相当于上边界已经移动了第二行。

同理,我们推断:

我们维护四个边界left, right, up, down,表示尚未走过的、可以移动的矩阵范围,起始时四个边界即矩阵的边界。当每次遇到新的边界的时候,需要把移动方向顺时针旋转90度,同时把刚刚走过的那个边界线(这条边界线上所有元素已经遍历过)需要向矩阵内移动,即缩小了边界。当所有的位置都被遍历了一次,则停止。

python代码如下,核心是每次遇到新的边界时,顺时针修改移动方向,并且将老边界内移。

保存已经走过的位置

一个比较蠢的实现方式:使用一个二维数组保存哪些走过了。这样遍历的时候,如果发现走过了就停止。因为while断开了,所以在当前的循环方向上要回退一格,然后移动行、列。

class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
visited = [[0] * n for _ in range(n)]
matrix = [[0] * n for _ in range(n)]
self.row, self.col = 0, 0
self.curr = 1
def spiral():
move = False
while self.col < n and not visited[self.row][self.col]:
matrix[self.row][self.col] = self.curr
self.curr += 1
visited[self.row][self.col] = 1
self.col += 1
move = True
self.col -= 1
self.row += 1
while self.row < n and not visited[self.row][self.col]:
matrix[self.row][self.col] = self.curr
self.curr += 1
visited[self.row][self.col] = 1
self.row += 1
move = True
self.row -= 1
self.col -= 1
while self.col >= 0 and not visited[self.row][self.col]:
matrix[self.row][self.col] = self.curr
self.curr += 1
visited[self.row][self.col] = 1
self.col -= 1
move = True
self.col += 1
self.row -= 1
while self.row >= 0 and not visited[self.row][self.col]:
matrix[self.row][self.col] = self.curr
self.curr += 1
visited[self.row][self.col] = 1
self.row -= 1
move = True
self.row += 1
self.col += 1
if move:
spiral()
spiral()
return matrix

日期

2018 年 3 月 13 日
2019 年 9 月 13 日 —— 一年半后的做法明显变得简单了~

【LeetCode】59. Spiral Matrix II 解题报告(Python)的更多相关文章

  1. LeetCode: Spiral Matrix II 解题报告-三种方法解决旋转矩阵问题

    Spiral Matrix IIGiven an integer n, generate a square matrix filled with elements from 1 to n2 in sp ...

  2. LeetCode: 59. Spiral Matrix II(Medium)

    1. 原题链接 https://leetcode.com/problems/spiral-matrix-ii/description/ 2. 题目要求 给定一个正整数n,求出从1到n平方的螺旋矩阵.例 ...

  3. [LeetCode] 59. Spiral Matrix II 螺旋矩阵 II

    Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. For ...

  4. Leetcode#59 Spiral Matrix II

    原题地址 相比于Spiral Matrix(参见这篇文章)要简单一些,因为是方阵,所以代码简洁一些. 注意当n是奇数的时候,中心小块要单独赋值(代码21行) 代码: vector<vector& ...

  5. LeetCode 59. Spiral Matrix II (螺旋矩阵之二)

    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...

  6. [leetcode]59. Spiral Matrix II螺旋遍历矩阵2

    Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral or ...

  7. Leetcode 54. Spiral Matrix & 59. Spiral Matrix II

    54. Spiral Matrix [Medium] Description Given a matrix of m x n elements (m rows, n columns), return ...

  8. leetcode 54. Spiral Matrix 、59. Spiral Matrix II

    54题是把二维数组安卓螺旋的顺序进行打印,59题是把1到n平方的数字按照螺旋的顺序进行放置 54. Spiral Matrix start表示的是每次一圈的开始,每次开始其实就是从(0,0).(1,1 ...

  9. 【leetcode】59.Spiral Matrix II

    Leetcode59 Spiral Matrix II Given an integer n, generate a square matrix filled with elements from 1 ...

随机推荐

  1. html5的canvas鼠标点击画圆

    <!doctype html><html lang="en"> <head> <meta charset="UTF-8" ...

  2. 使用Mybatis出现的问题+配置优化+ResultMap

    一.可能出现的问题 1.Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: ...

  3. 一次线上GC故障解决过程记录

    排查了三四个小时,终于解决了这个GC问题,记录解决过程于此,希望对大家有所帮助.本文假定读者已具备基本的GC常识和JVM调优知识,关于JVM调优工具使用可以查看我在同一分类下的另一篇文章: http: ...

  4. python写的多项式符号乘法

    D:\>poly.py(x - 1) * (x^2 + x + 1) = x^3 - 1 1 import ply.lex as lex # pip install ply 2 import p ...

  5. Spark(十六)【SparkStreaming基本使用】

    目录 一. SparkStreaming简介 1. 相关术语 2. SparkStreaming概念 3. SparkStreaming架构 4. 背压机制 二. Dstream入门 1. WordC ...

  6. 关于form表单提交ajaxForm和ajaxSubmit的用法与区别

    前几天在学习form表单提交时看到这两种方法,这两种方法都是实现form的ajax提交的方法,看了很多资料还是不太明白其用法和区别,最后直接自己写demo,很快就理解,所以说实操是学习的最快捷直接的途 ...

  7. OpenStack之四: keystone验证服务(端口5000)

    #官网地址:https://docs.openstack.org/keystone/stein/install/keystone-install-rdo.html #:创建库,并授权 MariaDB ...

  8. 【Python】【Module】json and pickle

    Python中用于序列化的两个模块 json     用于[字符串]和 [python基本数据类型] 间进行转换 pickle   用于[python特有的类型] 和 [python基本数据类型]间进 ...

  9. Linux下部署Java项目(jetty作为容器)常用脚本命令

    startup.sh #!/bin/bash echo $(basename $(pwd)) "jetty started" cd jetty nohup java -Xmx8g ...

  10. 【Linux】【RedHat】下载 安装 注册

    RedHat 下载 安装 注册 记录 因为找入口太麻烦了,所以写了篇博文记录下来大致入口@萌狼蓝天 注册 点击进入注册地址(https://www.redhat.com/wapps/ugc/regis ...