Skip to content

Commit 4647c64

Browse files
author
Li Li
committed
add code of 54
1 parent d2978d7 commit 4647c64

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
traverse right and increment rowBegin, then traverse down and decrement colEnd,
3+
traverse left and decrement rowEnd, and finally I traverse up and increment colBegin.
4+
5+
The only tricky part is that when traverse left or up, we have to check whether the
6+
row or col still exists to prevent duplicates.
7+
*/
8+
public class Solution {
9+
public IList<int> SpiralOrder(int[,] matrix) {
10+
List<int> res = new List<int>();
11+
if (matrix.GetLength(0) == 0) {
12+
return res;
13+
}
14+
int rowBegin = 0;
15+
int rowEnd = matrix.GetLength(0) - 1;
16+
int colBegin = 0;
17+
int colEnd = matrix.GetLength(1) - 1;
18+
while (rowBegin <= rowEnd && colBegin <= colEnd) {
19+
// traverse right
20+
for (int i = colBegin; i <= colEnd; i++) {
21+
res.Add(matrix[rowBegin, i]);
22+
}
23+
rowBegin++;
24+
// traverse down
25+
for (int i = rowBegin; i <= rowEnd; i++) {
26+
res.Add(matrix[i, colEnd]);
27+
}
28+
colEnd--;
29+
if (rowBegin <= rowEnd) {
30+
// traverse left
31+
for (int i = colEnd; i >= colBegin; i--) {
32+
res.Add(matrix[rowEnd, i]);
33+
}
34+
}
35+
rowEnd--;
36+
if (colBegin <= colEnd) {
37+
// traverse up
38+
for (int i = rowEnd; i >= rowBegin; i--) {
39+
res.Add(matrix[i, colBegin]);
40+
}
41+
}
42+
colBegin++;
43+
}
44+
return res;
45+
}
46+
}

0 commit comments

Comments
 (0)