Skip to content

Commit ca4eeb5

Browse files
author
applewjg
committed
SpiralMatrix
Change-Id: I286067954e3c6fe23dde7538a004bae96c810920
1 parent 69b90ab commit ca4eeb5

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

SpiralMatrix.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Spiral Matrix
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/spiral-matrix/
7+
Notes:
8+
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
9+
For example,
10+
Given the following matrix:
11+
[
12+
[ 1, 2, 3 ],
13+
[ 4, 5, 6 ],
14+
[ 7, 8, 9 ]
15+
]
16+
You should return [1,2,3,6,9,8,7,4,5].
17+
18+
Solution: ...
19+
*/
20+
public class Solution {
21+
public List<Integer> spiralOrder(int[][] matrix) {
22+
ArrayList<Integer> res = new ArrayList<Integer>();
23+
if (matrix.length == 0 || matrix[0].length == 0) return res;
24+
int n = matrix.length, m = matrix[0].length, row = 0, col = -1;
25+
while (true) {
26+
for (int i = 0; i < m; ++i) res.add(matrix[row][++col]);
27+
if (--n == 0) break;
28+
for (int i = 0; i < n; ++i) res.add(matrix[++row][col]);
29+
if (--m == 0) break;
30+
for (int i = 0; i < m; ++i) res.add(matrix[row][--col]);
31+
if (--n == 0) break;
32+
for (int i = 0; i < n; ++i) res.add(matrix[--row][col]);
33+
if (--m == 0) break;
34+
}
35+
return res;
36+
}
37+
}

SpiralMatrixII.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Spiral Matrix II
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/spiral-matrix-ii/
7+
Notes:
8+
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
9+
For example,
10+
Given n = 3,
11+
You should return the following matrix:
12+
[
13+
[ 1, 2, 3 ],
14+
[ 8, 9, 4 ],
15+
[ 7, 6, 5 ]
16+
]
17+
18+
Solution: ...
19+
*/
20+
public class Solution {
21+
public int[][] generateMatrix(int n) {
22+
if (n <= 0) return new int[0][0];
23+
int[][] res = new int[n][n];
24+
int m = n, row = 0, col = -1, num = 0;
25+
while (true) {
26+
for (int i = 0; i < m; ++i) res[row][++col] = ++num;
27+
if (--n == 0) break;
28+
for (int i = 0; i < n; ++i) res[++row][col] = ++num;
29+
if (--m == 0) break;
30+
for (int i = 0; i < m; ++i) res[row][--col] = ++num;
31+
if (--n == 0) break;
32+
for (int i = 0; i < n; ++i) res[--row][col] = ++num;
33+
if (--m == 0) break;
34+
}
35+
return res;
36+
}
37+
}

0 commit comments

Comments
 (0)