54. Spiral Matrix
Tags:
Medium
Skills:
Matrix
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Để giải bài toán Spiral Matrix trên LeetCode, bạn có thể sử dụng cách tiếp cận dựa trên việc thu hẹp các biên của ma trận (top, bottom, left, right) khi duyệt các phần tử theo thứ tự xoắn ốc. Dưới đây là một số ý tưởng và cách triển khai:
Approach
top, bottom, left, và right để đại diện cho bốn biên của ma trận.top++, bottom--, left++, right--) để tiếp tục duyệt phần ma trận chưa được xử lý.top > bottom hoặc left > right, việc duyệt kết thúc.Solution
1function spiralOrder(matrix: number[][]): number[] {
2 const res: number[] = [];
3 if (matrix.length === 0) return res;
4
5 let top = 0;
6 let bottom = matrix.length - 1;
7 let left = 0;
8 let right = matrix[0].length - 1;
9
10 while (top <= bottom && left <= right) {
11 // Top row: left -> right
12 for (let i = left; i <= right; i++) {
13 res.push(matrix[top][i]);
14 }
15 top++;
16
17 // Right column: top -> bottom
18 for (let i = top; i <= bottom; i++) {
19 res.push(matrix[i][right]);
20 }
21 right--;
22
23 // Bottom row: right -> left
24 if (top <= bottom) {
25 for (let i = right; i >= left; i--) {
26 res.push(matrix[bottom][i]);
27 }
28 bottom--;
29 }
30
31 // Left column: bottom -> top
32 if (left <= right) {
33 for (let i = bottom; i >= top; i--) {
34 res.push(matrix[i][left]);
35 }
36 left++;
37 }
38 }
39
40 return res;
41}
42