59. Spiral Matrix II
2018-03-14 12:10
459 查看
题目描述:Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.For example,
Given n =
You should return the following matrix:
给定一个整数,旋转输出一个n * n的矩阵。基本思路就是先初始化一个全为零的矩阵,像之前循环输出矩阵一样遍历,依次赋值就可以了。
我的代码:class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = [[0] * n for _ in range(n)]
num = 1
rb, re, cb, ce = 0, n - 1, 0, n - 1
while rb <= re and cb <= ce:
for i in range(cb, ce + 1):
matrix[rb][i] = num
num += 1
rb += 1
for i in range(rb, re + 1):
matrix[i][ce] = num
num += 1
ce -= 1
for i in range(ce, cb - 1, -1):
matrix[re][i] = num
num += 1
re -= 1
for i in range(re, rb - 1, -1):
matrix[i][cb] = num
num += 1
cb += 1
return matrix
Discuss:def generateMatrix(self, n): # Stefan大佬是真的强,这个思路无敌,膜拜Orz。
A = [[0] * n for _ in range(n)]
i, j, di, dj = 0, 0, 0, 1
for k in xrange(n*n):
A[i][j] = k + 1
if A[(i+di)%n][(j+dj)%n]:
di, dj = dj, -di
i += di
j += dj
return A学到:
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]我的思路:
给定一个整数,旋转输出一个n * n的矩阵。基本思路就是先初始化一个全为零的矩阵,像之前循环输出矩阵一样遍历,依次赋值就可以了。
我的代码:class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = [[0] * n for _ in range(n)]
num = 1
rb, re, cb, ce = 0, n - 1, 0, n - 1
while rb <= re and cb <= ce:
for i in range(cb, ce + 1):
matrix[rb][i] = num
num += 1
rb += 1
for i in range(rb, re + 1):
matrix[i][ce] = num
num += 1
ce -= 1
for i in range(ce, cb - 1, -1):
matrix[re][i] = num
num += 1
re -= 1
for i in range(re, rb - 1, -1):
matrix[i][cb] = num
num += 1
cb += 1
return matrix
Discuss:def generateMatrix(self, n): # Stefan大佬是真的强,这个思路无敌,膜拜Orz。
A = [[0] * n for _ in range(n)]
i, j, di, dj = 0, 0, 0, 1
for k in xrange(n*n):
A[i][j] = k + 1
if A[(i+di)%n][(j+dj)%n]:
di, dj = dj, -di
i += di
j += dj
return A学到:
相关文章推荐
- 59. Spiral Matrix II
- LeetCode54/59 Spiral Matrix I/II
- 59. Spiral Matrix II
- 59. Spiral Matrix II && 54. Spiral Matrix
- 【leetcode】59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59 --- Spiral Matrix II
- 【leetcode】59.Spiral Matrix II
- Leetcode 59 Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- 【LeetCode】C# 59、Spiral Matrix II
- 59. Spiral Matrix II
- [59] Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- [LeetCode OJ]59. Spiral Matrix II
- LeetCode-59-Spiral Matrix II(Array)-Medium
- 59. Spiral Matrix II
- 54. Spiral Matrix&59. Spiral Matrix II
- LeetCode_59---Spiral Matrix II