TGViewer
Python | LeetCode Python | LeetCode @easy_python_task · 9.04K subscribers
Post #2378 619
Задача: 1424. Diagonal Traverse II
Сложность: medium

Дан двумерный целочисленный массив nums, верните все элементы nums в диагональном порядке.

Пример:
Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]


👨‍💻 Алгоритм:

1⃣Инициализируйте очередь с (0, 0) и список ответов ans.

2⃣Пока очередь не пуста:
Извлеките (row, col) из очереди.
Добавьте nums[row][col] в ans.
Если col == 0 и row + 1 в пределах массива, добавьте (row + 1, col) в очередь.
Если col + 1 в пределах текущей строки, добавьте (row, col + 1) в очередь.

3⃣Верните ans.

😎 Решение:
from collections import deque

class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
queue = deque([(0, 0)])
ans = []

while queue:
row, col = queue.popleft()
ans.append(nums[row][col])

if col == 0 and row + 1 < len(nums):
queue.append((row + 1, col))

if col + 1 < len(nums[row]):
queue.append((row, col + 1))

return ans


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_python_task
  1. Oct 10, 2026Post #2435
  2. Oct 10, 2026Задача: 1249. Minimum Remove to Make Valid Parentheses Сложность: medium Дана строка s из…
  3. Oct 9, 2026Post #2433
  4. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для Python разработчика, которые нигде больше не п…
  5. Oct 4, 2026Задача: 958. Check Completeness of a Binary Tree Сложность: medium Дан корень бинарного де…
  6. Oct 4, 2026Задача: 949. Largest Time for Given Digits Сложность: medium Учитывая массив arr из 4 цифр…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →