LeetCode 59. Spiral Matrix II(Python)
来源:互联网 发布:阿里云未备案域名解析 编辑:程序博客网 时间:2024/05/30 04:55
题目描述:
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 ]
]
思路:
螺旋式绕圈赋值即可,停止条件即当所有均赋值完。
AC代码:
def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ if n == 0: return [] res = [[0 for x in range(n)] for x in range(n)] cnt, choice = 1, 0 i, j = 0, 0 weight = 1 res[0][0] = 1 while cnt < n * n: if choice == 0: j += 1 res[i][j] = cnt + 1 if j == n - weight: choice = 1 elif choice == 1: i += 1 res[i][j] = cnt + 1 if i == n - weight: choice = 2 elif choice == 2: j -= 1 res[i][j] = cnt + 1 if j == weight - 1: choice = 3 weight += 1 elif choice == 3: i -= 1 res[i][j] = cnt + 1 if i == weight - 1: choice = 0 cnt += 1 return res
阅读全文
0 0
- LeetCode 59. Spiral Matrix II(Python)
- 【Leetcode】【python】Spiral Matrix/Spiral Matrix II
- 59. Spiral Matrix II Leetcode Python
- [LeetCode]59.Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- [Leetcode] 59. Spiral Matrix II
- [leetcode] 59.Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- 59. Spiral Matrix II LeetCode
- [leetcode] 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 59. Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- LeetCode - 59. Spiral Matrix II
- ViewPager+Tablayout的联动效果
- DuiLib界面库学习笔记(源码获取和编译)
- 分类和回归的区别和联系
- hdu5832(大数取模)
- CodeChef:Chef Anup(数学)
- LeetCode 59. Spiral Matrix II(Python)
- 关于Thinkphp 使用uploadify上传文件的问题(data返回值的问题)
- 《时间有泪》
- Python爬虫——自制简单的搜索引擎
- jquery $.trim()方法
- 单链表实现一元多项式乘法
- 【UWP开发】unity发布win10报错Exception: Failed to restore NuGet packages
- 【CUGBACM15级BC第22场 A】hdu 5142 NPY and FFT
- FZU 2282 Wand(错排+费马小定理)