forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem3.java
More file actions
107 lines (74 loc) · 2.2 KB
/
problem3.java
File metadata and controls
107 lines (74 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//We use 4 boundaries to simulate spiral traversal:
//
//top → top row
//
//bottom → bottom row
//
//left → left column
//
//right → right column
//
//Traversal order:
//
//Left → Right (top row)
//
//Top → Bottom (right column)
//
//Right → Left (bottom row)
//
//Bottom → Top (left column)
//
//After each step, shrink the boundary.
//
// Time: O(m × n)
//Space: O(1) (excluding result)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
// Number of rows
int m = matrix.length;
// Number of columns
int n = matrix[0].length;
// Define boundaries
int top = 0; // starting row
int bottom = m - 1; // ending row
int left = 0; // starting column
int right = n - 1; // ending column
// Result list to store spiral order
List<Integer> result = new ArrayList<>();
// Continue until all boundaries are crossed
while(top <= bottom && left <= right) {
// 1. Traverse LEFT → RIGHT on TOP row
for(int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
// Move top boundary down
top++;
// 2. Traverse TOP → BOTTOM on RIGHT column
for(int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
// Move right boundary left
right--;
// 3. Traverse RIGHT → LEFT on BOTTOM row
// Check to avoid duplicate row traversal
if(top <= bottom) {
for(int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
// Move bottom boundary up
bottom--;
}
// 4. Traverse BOTTOM → TOP on LEFT column
// Check to avoid duplicate column traversal
if(left <= right) {
for(int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
// Move left boundary right
left++;
}
}
// Return spiral traversal
return result;
}
}