mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 13:12:44 +00:00
docs(docs): add new problem pages for Rotate Image, Spiral Matrix, and Add Two Numbers
This commit is contained in:
1 parent
a3ae16ad96
commit
090f3d6719
3 files changed
+153
No files matched your search
@@ -0,0 +1,59 @@
|
||||
---
|
||||
title: '54. Spiral Matrix'
|
||||
description: Given an m x n matrix, return all elements of the matrix in spiral order
|
||||
sidebar:
|
||||
label: 'Spiral Matrix'
|
||||
badge: 'Medium'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Matrix Index Math</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `matrix = [[1,2,3],[4,5,6],[7,8,9]]`
|
||||
- Output: `[1,2,3,6,9,8,7,4,5]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `matrix = [[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]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- `m == matrix.length`
|
||||
- `n == matrix[i].length`
|
||||
- `1 <= m, n <= 10`
|
||||
- `-100 <= matrix[i][j] <= 100`
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
class Solution:
|
||||
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
|
||||
res = []
|
||||
top, bottom = 0, len(matrix) - 1
|
||||
left, right = 0, len(matrix[0]) - 1
|
||||
|
||||
while top <= bottom and left <= right:
|
||||
# 1. Top Row
|
||||
for c in range(left, right + 1):
|
||||
res.append(matrix[top][c])
|
||||
top += 1
|
||||
|
||||
# 2. Right Column
|
||||
for r in range(top, bottom + 1):
|
||||
res.append(matrix[r][right])
|
||||
right -= 1
|
||||
|
||||
# 3. Bottom Row
|
||||
if top <= bottom:
|
||||
for c in range(right, left - 1, -1):
|
||||
res.append(matrix[bottom][c])
|
||||
bottom -= 1
|
||||
|
||||
# 4. Left Column
|
||||
if left <= right:
|
||||
for r in range(bottom, top - 1, -1):
|
||||
res.append(matrix[r][left])
|
||||
left += 1
|
||||
|
||||
return res
|
||||
```
|
||||
Reference in new issue
Block a user