Skip to content

Commit 455331d

Browse files
Spiral Matrix
1 parent 9552add commit 455331d

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ Your ideas/fixes/algorithms are more than welcome!
205205
|60|[Permutation Sequence](https://leetcode.com/problems/permutation-sequence/)|[Solution](../../blob/master/src/stevesun/algorithms/PermutationSequence.java)|?|?|Medium|
206206
|58|[Length of Last Word](https://leetcode.com/problems/length-of-last-word/)|[Solution](../../blob/master/src/stevesun/algorithms/LengthofLastWord.java)|O(n)|O(1)|Easy|
207207
|56|[Merge Intervals](https://leetcode.com/problems/merge-intervals/)|[Solution](../../blob/master/src/stevesun/algorithms/MergeIntervals.java)|O(n*logn)|O(1)|Hard|
208+
|54|[Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)|[Solution](../../blob/master/src/stevesun/algorithms/SpiralMatrix.java)|O(m*n)|O(m*n)|Medium|
208209
|53|[Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)|[Solution](../../blob/master/src/stevesun/algorithms/MaximumSubarray.java)|O(n)|O(1)|Medium|
209210
|50|[Pow(x, n)](https://leetcode.com/problems/powx-n/)|[Solution](../../blob/master/src/stevesun/algorithms/PowXN.java)|O(logn)|O(logn)|Medium|
210211
|47|[Permutations II](https://leetcode.com/problems/permutations-ii/)|[Solution](../../blob/master/src/stevesun/algorithms/PermutationsII.java)|O(n*n!)|O(n)|Medium|Backtracking
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package stevesun.algorithms;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
8+
9+
For example,
10+
Given the following matrix:
11+
12+
[
13+
[ 1, 2, 3 ],
14+
[ 4, 5, 6 ],
15+
[ 7, 8, 9 ]
16+
]
17+
You should return [1,2,3,6,9,8,7,4,5].
18+
*/
19+
public class SpiralMatrix {
20+
21+
public List<Integer> spiralOrder(int[][] matrix) {
22+
ArrayList<Integer> res = new ArrayList();
23+
int row = matrix.length;
24+
25+
if(row == 0){
26+
return res;
27+
}
28+
int col = matrix[0].length;
29+
int len = row*col;
30+
31+
int i = 0, j = 0, rowStart = 1, colStart = 0;
32+
while(res.size() <= len){
33+
for(; j < col; j++){
34+
res.add(matrix[i][j]);
35+
}
36+
if(res.size() == len)
37+
break;
38+
col--;
39+
j--;
40+
i++;
41+
for(; i < row; i++){
42+
res.add(matrix[i][j]);
43+
}
44+
if(res.size() == len)
45+
break;
46+
row--;
47+
i--;
48+
j--;
49+
for(; j >= colStart; j--){
50+
res.add(matrix[i][j]);
51+
}
52+
if(res.size() == len)
53+
break;
54+
colStart++;
55+
j++;
56+
i--;
57+
for(; i >= rowStart; i--){
58+
res.add(matrix[i][j]);
59+
}
60+
if(res.size() == len)
61+
break;
62+
rowStart++;
63+
i ++;
64+
j++;
65+
}
66+
return res;
67+
}
68+
69+
}

0 commit comments

Comments
 (0)