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 all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Solution
Approach 1. 按照外围圈遍历
用r标记圈数(r = 0开始),同时(r, r)也为起始坐标。
注意:
对于 [6 7],避免再次回转到6,应加入判断条件:m > 1
对于[7
8
9] 避免再次回转到7,应加入判断条件:n > 1
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
r = 0
ret = []
if not matrix or not matrix[0]:
return ret
m, n = len(matrix), len(matrix[0])
while m >= 1 and n >= 1:
for i in range(n):
ret.append(matrix[r][r + i])
for i in range(m - 1):
ret.append(matrix[r + 1 + i][r + n - 1]) if m > 1:
for i in range(n - 1):
ret.append(matrix[r + m - 1][r + n - 1 - 1 - i])
if n > 1:
for i in range(m - 2):
ret.append(matrix[r + m - 1 -1 - i][r])
m -= 2
n -= 2
r += 1
return ret
Beats: 75.70%
Runtime: 36ms
Approach 2. Simulation
参考Leetcode官方Solution
Intuition
Draw the path that the spiral makes. We know that the path should turn clockwise whenever it would go out of bounds or into a cell that was previously visited.
Algorithm
Let the array have R rows and C columns. seen[r][c] denotes that the cell on the r-th row and c-th column was previously visited.
Our current position is (r, c), facing direction \text{di}di, and we want to visit R x C total cells.
As we move through the matrix, our candidate next position is (cr, cc).
If the candidate is in the bounds of the matrix and unseen, then it becomes our next position;
otherwise, our next position is the one after performing a clockwise turn.
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix: return []
R, C = len(matrix), len(matrix[0])
seen = [[False] * C for _ in matrix]
ans = []
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
r = c = di = 0 for _ in range(R * C):
ans.append(matrix[r][c])
seen[r][c] = True
cr, cc = r + dr[di], c + dc[di]
if 0 <= cr < R and 0 <= cc < C and not seen[cr][cc]:
r, c = cr, cc
else:
di = (di + 1) % 4
r, c = r + dr[di], c + dc[di]
return ans
Beats: 75.70%
Runtime: 36ms
59. Spiral Matrix II [Medium]
Description
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Solution
用r标记圈数
1 2 3 | 4
-------- |
12| 13 14 | 5
11| 16 15 | 6
10| 9 8 7
------------
注意当n == 1时,for循环中n - 1 = 0,则不能执行,
如input = 3 时,9不能输出,
所以需要单独写 n == 1 时的情况。
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = [([0] * n) for _ in range(n)]
cnt = 1
r = 0
while n >= 2:
for i in range(n - 1):
matrix[r][r + i] = cnt
cnt += 1
for i in range(n - 1):
matrix[r + i][r + n - 1] = cnt
cnt += 1
for i in range(n - 1):
matrix[r + n - 1][r + n - 1 - i] = cnt
cnt += 1
for i in range(n - 1):
matrix[r + n - 1 - i][r] = cnt
cnt += 1 n -= 2
r += 1
if n == 1:
matrix[r][r] = cnt
return matrix
Beats: 48.93%
Runtime: 44ms
Leetcode 54. Spiral Matrix & 59. Spiral Matrix II的更多相关文章
- 54. Spiral Matrix && 59. Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral ord ...
- LeetCode 54. 螺旋矩阵(Spiral Matrix) 剑指offer-顺时针打印矩阵
题目描述 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素. 示例 1: 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, ...
- leetcode 54. Spiral Matrix 、59. Spiral Matrix II
54题是把二维数组安卓螺旋的顺序进行打印,59题是把1到n平方的数字按照螺旋的顺序进行放置 54. Spiral Matrix start表示的是每次一圈的开始,每次开始其实就是从(0,0).(1,1 ...
- leetcode@ [54/59] Spiral Matrix & Spiral Matrix II
https://leetcode.com/problems/spiral-matrix/ Given a matrix of m x n elements (m rows, n columns), r ...
- [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 ...
- 59. Spiral Matrix && Spiral Matrix II
Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the matri ...
- LeetCode 54. Spiral Matrix(螺旋矩阵)
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or ...
- Leetcode 54:Spiral Matrix 螺旋矩阵
54:Spiral Matrix 螺旋矩阵 Given a matrix of m x n elements (m rows, n columns), return all elements of t ...
- [array] leetcode - 54. Spiral Matrix - Medium
leetcode-54. Spiral Matrix - Medium descrition GGiven a matrix of m x n elements (m rows, n columns) ...
随机推荐
- Git错误
$ rm -rf .git $ git config --global core.autocrlf false $git init $git add . ---------------------- ...
- 开发工具--Eclipse使用及常见问题解决
怎么查询Eclipse版本号: 方法一: 方法二: Eclipse安装目录下面找到readme文件夹,里边有个网页打开就可以看到当前版本; Eclipse汉化改为英文: Eclipse Mybatis ...
- c# 常用数据库封装
我不为大家贴代码了,没有意思,有点多,我主要给大家介绍一下,源码会上传CSDN和GIT:我定义了一个ADO.NET操作接口,所有按照接口封装 1.sqlite数据库(需要SQLite.Interop. ...
- IPC进程间通信---信号量
信号量 信号量:信号量是一个计数器,常用于处理进程或线程的同步问题,特别是对于临界资源访问的同步.临界资源可以 理解为在某一时刻只能由一个进程或线程操作的资源,这里的资源可以是一段代码.一个变量或某种 ...
- 洛谷P3804 【模板】后缀自动机
题目描述 给定一个只包含小写字母的字符串 SS , 请你求出 SS 的所有出现次数不为 11 的子串的出现次数乘上该子串长度的最大值. 输入输出格式 输入格式: 一行一个仅包含小写字母的字符串 SS ...
- BZOJ1607: [Usaco2008 Dec]Patting Heads 轻拍牛头(模拟 调和级数)
Time Limit: 3 Sec Memory Limit: 64 MBSubmit: 3031 Solved: 1596[Submit][Status][Discuss] Descriptio ...
- 线程池的类型以及执行线程submit()和execute()的区别
就跟题目说的一样,本篇博客,本宝宝主要介绍两个方面的内容,其一:线程池的类型及其应用场景:其二:submit和execute的区别.那么需要再次重申的是,对于概念性的东西,我一般都是从网上挑选截取,再 ...
- JQuery实现聊天对话框
效果图如下: HTML代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...
- Linux下文件字符编码格式检测和转换
目前多数情况下, 我们遇到的非英文字符文件都是使用UTF-8编码的, 这时一般我们查看这些文件的内容都不会有问题. 不过有时, 我们有可能会遇到非UTF-8编码的文件, 比如中文的GBK编码, 或者俄 ...
- HTML中的【块】与【内嵌】
块元素与内嵌元素 块的特征 默认独占一行 没有宽度时默认撑满一行 支持所有的css命令 内嵌的特征 同行可以连续跟同类的标签 内容撑开宽度 不支持宽高 不支持上下的内外边距 代码换行被解析 块与内嵌的 ...