-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
110 lines (96 loc) · 2.94 KB
/
SpiralMatrix.java
File metadata and controls
110 lines (96 loc) · 2.94 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package com.leetcode.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SpiralMatrix {
/**
* 给你一个 m 行 n 列的矩阵matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
*
* 示例 1:
* 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
* 输出:[1,2,3,6,9,8,7,4,5]
*
* 示例 2:
* 输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
* 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
*
* 提示:
* m == matrix.length
* n == matrix[i].length
* 1 <= m, n <= 10
* -100 <= matrix[i][j] <= 100
*
* 链接:https://leetcode.cn/problems/spiral-matrix
* @param matrix
* @return
*/
public List<Integer> spiralOrder(int[][] matrix) {
if(matrix==null || matrix[0].length==0){
return null;
}
int m = matrix.length,n = matrix[0].length;
int top = 0,bottom = m-1, left=0,right = n-1;
List<Integer> ans = new ArrayList<>(m*n);
while(top<=bottom && left<=right){
//从左到右
for(int i=left;i<=right;i++){
ans.add(matrix[top][i]);
}
top++;
//从上到下
for(int i=top;i<=bottom;i++){
ans.add(matrix[i][right]);
}
right--;
// 单行,单列的情况下
if(left>right||top>bottom) break;
//从右向左
for(int i=right;i>=left;i--){
ans.add(matrix[bottom][i]);
}
bottom--;
//从下向上
for(int i=bottom;i>=top;i--){
ans.add(matrix[i][left]);
}
left++;
}
return ans;
}
public static int[] spiralArray(int[][] array) {
int m = array.length, n = array[0].length;
int top = 0, bottom = array.length-1;
int left = 0, right = array[0].length-1;
int [] results = new int[m*n];
int index = 0;
while(top<=bottom && left<=right) {
// 向右
for(int i= left;i<=right;i++){
results[index++] = array[top][i];
}
top++;
// 向下
for(int i=top;i<=bottom;i++){
results[index++] = array[i][right];
}
right--;
if(left>right || top>bottom) break;
// 向左
for(int i = right;i>=left;i--){
results[index++] = array[bottom][i];
}
bottom--;
// 向上
for(int i = bottom;i>=top;i--) {
results[index++] = array[i][left];
}
left++;
}
return results;
}
public static void main(String[] args) {
int [][]array = {{1,2,3},{4,5,6},{7,8,9}};
int[] ints = spiralArray(array);
System.out.println(Arrays.toString(ints));
}
}