Skip to content

Commit eec57c1

Browse files
solves spiral matrix
1 parent bef9cf0 commit eec57c1

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
| 49 | [Group Anagrams](https://leetcode.com/problems/group-anagrams) | [![Java](assets/java.png)](src/GroupAnagrams.java) | |
5353
| 50 | [Pow(x,n)](https://leetcode.com/problems/powx-n) | [![Java](assets/java.png)](src/Powxn.java) | |
5454
| 53 | [Maximum SubArray](https://leetcode.com/problems/maximum-subarray) | [![Java](assets/java.png)](src/MaximumSubArray.java) [![Python](assets/python.png)](python/maximum_sum_subarray.py) | |
55+
| 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix) | [![Java](assets/java.png)](src/SpiralMatrix.java) | |
5556
| 55 | [Jump Game](https://leetcode.com/problems/jump-game) | [![Java](assets/java.png)](src/JumpGame.java) | |
5657
| 58 | [Length of Last Word](https://leetcode.com/problems/length-of-last-word) | [![Java](assets/java.png)](src/LengthOfLastWord.java) [![Python](assets/python.png)](python/length_of_last_word.py) | |
5758
| 66 | [Plus One](https://leetcode.com/problems/plus-one) | [![Java](assets/java.png)](src/PlusOne.java) [![Python](assets/python.png)](python/plus_one.py) | |

Diff for: src/SpiralMatrix.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class SpiralMatrix {
5+
public List<Integer> spiralOrder(int[][] matrix) {
6+
final List<Integer> result = new ArrayList<>();
7+
final int rows = matrix.length, columns = matrix[0].length, elements = rows * columns;
8+
for (int i = 0, top = 0, bottom = rows, left = 0, right = columns ; ; ) {
9+
for (int row = top, column = left ; column < right ; column++, i++) {
10+
result.add(matrix[row][column]);
11+
}
12+
top++;
13+
if (i == elements) break;
14+
for (int row = top, column = right - 1 ; row < bottom ; row++, i++) {
15+
result.add(matrix[row][column]);
16+
}
17+
right--;
18+
if (i == elements) break;
19+
for (int row = bottom - 1, column = right - 1 ; column >= left ; column--, i++) {
20+
result.add(matrix[row][column]);
21+
}
22+
bottom--;
23+
if (i == elements) break;
24+
for (int row = bottom - 1, column = left ; row >= top ; row--, i++) {
25+
result.add(matrix[row][column]);
26+
}
27+
left++;
28+
if (i == elements) break;
29+
}
30+
return result;
31+
}
32+
}

0 commit comments

Comments
 (0)