mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
增加了一版更通俗易懂的Java代码
This commit is contained in:
@ -200,6 +200,79 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
public List<Integer> spiralOrder(int[][] matrix) {
|
||||||
|
List<Integer> res = new ArrayList<>(); // 存放结果
|
||||||
|
if (matrix.length == 0 || matrix[0].length == 0)
|
||||||
|
return res;
|
||||||
|
int rows = matrix.length, columns = matrix[0].length;
|
||||||
|
int startx = 0, starty = 0; // 定义每循环一个圈的起始位置
|
||||||
|
int loop = 0; // 循环次数
|
||||||
|
int offset = 1; // 每一圈循环,需要控制每一条边遍历的长度
|
||||||
|
while (loop < Math.min(rows, columns) / 2) {
|
||||||
|
int i = startx;
|
||||||
|
int j = starty;
|
||||||
|
// 模拟填充上行从左到右(左闭右开)
|
||||||
|
for (; j < columns - offset; j++) {
|
||||||
|
res.add(matrix[i][j]);
|
||||||
|
}
|
||||||
|
// 模拟填充右列从上到下(左闭右开)
|
||||||
|
for (; i < rows - offset; i++) {
|
||||||
|
res.add(matrix[i][j]);
|
||||||
|
}
|
||||||
|
// 模拟填充下行从右到左(左闭右开)
|
||||||
|
for (; j > starty; j--) {
|
||||||
|
res.add(matrix[i][j]);
|
||||||
|
}
|
||||||
|
// 模拟填充左列从下到上(左闭右开)
|
||||||
|
for (; i > startx; i--) {
|
||||||
|
res.add(matrix[i][j]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 起始位置加1 循环次数加1 并控制每条边遍历的长度
|
||||||
|
startx++;
|
||||||
|
starty++;
|
||||||
|
offset++;
|
||||||
|
loop++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果列或行中的最小值为奇数 则一定有未遍历的部分
|
||||||
|
// 可以自行画图理解
|
||||||
|
if (Math.min(rows, columns) % 2 == 1) {
|
||||||
|
// 当行大于列时 未遍历的部分是列
|
||||||
|
// (startx, starty)即下一个要遍历位置 从该位置出发 遍历完未遍历的列
|
||||||
|
// 遍历次数为rows - columns + 1
|
||||||
|
if (rows > columns) {
|
||||||
|
for (int i = 0; i < rows - columns + 1; i++) {
|
||||||
|
res.add(matrix[startx++][starty]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 此处与上面同理 遍历完未遍历的行
|
||||||
|
for (int i = 0; i < columns - rows + 1; i++) {
|
||||||
|
res.add(matrix[startx][starty++]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### Javascript
|
### Javascript
|
||||||
```
|
```
|
||||||
/**
|
/**
|
||||||
|
Reference in New Issue
Block a user