0%

Leetcode54. Spiral Matrix

Leetcode54. Spiral Matrix

题目描述

1
2
3
4
5
6
7
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

思路

有四个方向right, left, top, bottom.

  1. direction=”right”, 当到达最右边界时,代表本行输出结束,top++,
  2. direction=”bottom”,当到达最下边界时, right–,
  3. direction = “left”,当到达最左边界是 bottom–,
  4. direction=”top”,当到达top时候,left++,direction=”right”.

代码

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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
//result
List<Integer> result = new ArrayList&lt;&gt;();
if (matrix.length == 0) return result;
//获取行数---Y行
int lenY =matrix.length;
//获取列数---X列
int lenX = matrix[0].length;
String direction = &quot;right&quot;;
int left=0;
int right = lenX-1;
int down =0;
int up = lenY-1;
while(left&lt;=right &amp;&amp; down&lt;=up){
if(direction == &quot;right&quot;){
for(int i=left;i&lt;=right;i++){
result.add(matrix[down][i]);
}
down++;
direction = &quot;down&quot;;
}else if(direction==&quot;down&quot;){
for(int i=down;i&lt;=up;i++){
result.add(matrix[i][right]);
}
right--;
direction = &quot;left&quot;;
}else if(direction==&quot;left&quot;){
for(int i=right;i&gt;=left;i--){
result.add(matrix[up][i]);
}
up--;
direction =&quot;up&quot;;
}else if(direction==&quot;up&quot;){
for(int i=up;i&gt;=down;i--){
result.add(matrix[i][left]);
}
left++;
direction = &quot;right&quot;;
}
}
return result;
}
}
-------------本文结束感谢您的阅读-------------

Welcome to my other publishing channels