Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
60 lines (45 loc) · 1.69 KB

File metadata and controls

60 lines (45 loc) · 1.69 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package Algorithms;
import java.util.ArrayList;
public class SpiralOrder {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> result = new ArrayList<Integer>();
// remember such kinds of board.
if (matrix.length == 0 || matrix[0].length == 0) {
return result;
}
spiralOrderhelp(matrix, result, matrix.length, matrix[0].length);
return result;
}
// m, n: the middle m lines and n columns.
public void spiralOrderhelp(int[][] matrix, ArrayList<Integer> result, int m, int n) {
if (m <= 0 || n <= 0) {
return;
}
// setup the begin point.
int lineB = (matrix.length - m)/2;
int colB = (matrix[0].length - n)/2;
int line = lineB;
int col = colB-1; // begin from the first element.
while (col < colB+n-1) {
result.add(matrix[line][++col]);
}
while (line < lineB+m-1) {
result.add(matrix[++line][col]);
}
// eliminate the duplicate calculating.
while (col > colB && line != lineB) {
result.add(matrix[line][--col]);
}
// eliminate the duplicate calculating.
while (line > lineB+1 && col != colB) {
result.add(matrix[--line][col]);
}
spiralOrderhelp(matrix, result, m-2, n-2);
}
public static void main(String[] args) {
int[][] input = {{2,3}};
SpiralOrder test = new SpiralOrder();
ArrayList<Integer> result = test.spiralOrder(input);
System.out.printf(result.toString());
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.