From f5a5d2005e394f0d5de2adf9d88f839796f3267b Mon Sep 17 00:00:00 2001 From: GP Date: Sat, 18 May 2024 13:05:11 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E4=B8=80=E7=89=88?= =?UTF-8?q?=E6=9B=B4=E9=80=9A=E4=BF=97=E6=98=93=E6=87=82=E7=9A=84Java?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0054.螺旋矩阵.md | 73 +++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/problems/0054.螺旋矩阵.md b/problems/0054.螺旋矩阵.md index 4d54ccd6..d7cfc7bf 100644 --- a/problems/0054.螺旋矩阵.md +++ b/problems/0054.螺旋矩阵.md @@ -200,6 +200,79 @@ class Solution { } ``` +```java +class Solution { + public List spiralOrder(int[][] matrix) { + List 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 ``` /**