From b06601c58c08a8647c64af82034e41f1b06d8618 Mon Sep 17 00:00:00 2001 From: markwang Date: Sun, 28 Apr 2024 15:18:01 +0800 Subject: [PATCH 1/2] =?UTF-8?q?54.=E8=9E=BA=E6=97=8B=E7=9F=A9=E9=98=B5?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0054.螺旋矩阵.md | 76 +++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/problems/0054.螺旋矩阵.md b/problems/0054.螺旋矩阵.md index 4d54ccd6..175ae147 100644 --- a/problems/0054.螺旋矩阵.md +++ b/problems/0054.螺旋矩阵.md @@ -348,6 +348,82 @@ class Solution(object): return print_list ``` +### Go: + +```go +func spiralOrder(matrix [][]int) []int { + rows := len(matrix) + if rows == 0 { + return []int{} + } + columns := len(matrix[0]) + if columns == 0 { + return []int{} + } + res := make([]int, rows * columns) + startx, starty := 0, 0 // 定义每循环一个圈的起始位置 + loop := min(rows, columns) / 2 + mid := min(rows, columns) / 2 + count := 0 // 用来给矩阵中每一个空格赋值 + offset := 1 // 每一圈循环,需要控制每一条边遍历的长度 + for loop > 0 { + i, j := startx, starty + + // 模拟填充上行从左到右(左闭右开) + for ; j < starty + columns - offset; j++ { + res[count] = matrix[startx][j] + count++ + } + // 模拟填充右列从上到下(左闭右开) + for ; i < startx + rows - offset; i++ { + res[count] = matrix[i][j] + count++ + } + // 模拟填充下行从右到左(左闭右开) + for ; j > starty; j-- { + res[count] = matrix[i][j] + count++ + } + // 模拟填充左列从下到上(左闭右开) + for ; i > startx; i-- { + res[count] = matrix[i][starty] + count++ + } + + // 第二圈开始的时候,起始位置要各自加1, 例如:第一圈起始位置是(0, 0),第二圈起始位置是(1, 1) + startx++ + starty++ + + // offset 控制每一圈里每一条边遍历的长度 + offset += 2 + loop-- + } + + // 如果min(rows, columns)为奇数的话,需要单独给矩阵最中间的位置赋值 + if min(rows, columns) % 2 == 1 { + if rows > columns { + for i := mid; i < mid + rows - columns + 1; i++ { + res[count] = matrix[i][mid] + count++ + } + } else { + for i := mid; i < mid + columns - rows + 1; i++ { + res[count] = matrix[mid][i] + count++ + } + } + } + return res +} + +func min(x, y int) int { + if x < y { + return x + } + return y +} +``` +

From fda179fd7f0789e33f65b6bc5cb1c517a8a83104 Mon Sep 17 00:00:00 2001 From: markwang Date: Sun, 28 Apr 2024 15:21:11 +0800 Subject: [PATCH 2/2] =?UTF-8?q?54.=E8=9E=BA=E6=97=8B=E7=9F=A9=E9=98=B5?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0054.螺旋矩阵.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0054.螺旋矩阵.md b/problems/0054.螺旋矩阵.md index 175ae147..022eed66 100644 --- a/problems/0054.螺旋矩阵.md +++ b/problems/0054.螺旋矩阵.md @@ -348,7 +348,7 @@ class Solution(object): return print_list ``` -### Go: +### Go ```go func spiralOrder(matrix [][]int) []int {