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的更多相关文章

  1. 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 ...

  2. LeetCode 54. 螺旋矩阵(Spiral Matrix) 剑指offer-顺时针打印矩阵

    题目描述 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素. 示例 1: 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, ...

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

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

  4. 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 ...

  5. [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 ...

  6. 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 ...

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

  8. Leetcode 54:Spiral Matrix 螺旋矩阵

    54:Spiral Matrix 螺旋矩阵 Given a matrix of m x n elements (m rows, n columns), return all elements of t ...

  9. [array] leetcode - 54. Spiral Matrix - Medium

    leetcode-54. Spiral Matrix - Medium descrition GGiven a matrix of m x n elements (m rows, n columns) ...

随机推荐

  1. 使用TextView/EditText应该注意的地方,监听EditText,addTextChangedListener

    http://blog.csdn.net/huichengongzi/article/details/7818676 监听 EditText 控件: addTextChangedListener(ne ...

  2. CSU 1023 修路(二分+模拟)

    前段时间,某省发生干旱,B山区的居民缺乏生活用水,现在需要从A城市修一条通往B山区的路.假设有A城市通往B山区的路由m条连续的路段组成,现在将这m条路段承包给n个工程队(n ≤ m ≤ 300).为了 ...

  3. JavaScript中的Map和Set

    JavaScript的默认对象表示方法{}可以视为其他语言中的Map或者Dictionary的数据结构,即一组键值对. 但是JavaScript的对象有个小问题,就是键必须是字符串,但实际上Numbe ...

  4. Vue nodejs商城-订单模块

    一.订单列表渲染 新建OrderConfirm.vue订单确认页面,添加路由 src/router/index.js添加路由 import OrderConfirm from '@/views/Ord ...

  5. 兼容性良好的 sticky-footer 布局

    <div class="content"> <div class="content-wrapper"> <div class=&q ...

  6. Python实现爬虫从网络上下载文档

    最近在学习Python,自然接触到了爬虫,写了一个小型爬虫软件,从初始Url解析网页,使用正则获取待爬取链接,使用beautifulsoup解析获取文本,使用自己写的输出器可以将文本输出保存,具体代码 ...

  7. Layui上传文件以及数据表格

    layui对于一些前端小白来说,例如我,真的非常的好用,不用去花很多很多的心思在前端美化中,并且提高了很大的工作效率.所以建议一些觉得自己前端技术不是很强,但是想让前端美化一点的可以使用layui. ...

  8. WebMagic 启动例子报错

    报错内容: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/conn/Http ...

  9. Ubuntu16.04采用FastCGI方式部署Flask web框架

    1    部署nginx 1.1    安装nginx服务 root@desktop:~# apt-get install nginx -y 1.2    验证nginx服务是否启动 root@des ...

  10. JSP/Servlet开发——第二章 JSP数据交互(二)

    1. JSP 内置对象 application: ●application 对象类似于系统的 "全局变量", 用于同一个应用内的所有用户之问的数据共享: ●application对 ...