@@ -348,6 +348,82 @@ class Solution(object):
348348 return print_list
349349```
350350
351+ ### Go
352+
353+ ``` go
354+ func spiralOrder (matrix [][]int ) []int {
355+ rows := len (matrix)
356+ if rows == 0 {
357+ return []int {}
358+ }
359+ columns := len (matrix[0 ])
360+ if columns == 0 {
361+ return []int {}
362+ }
363+ res := make ([]int , rows * columns)
364+ startx , starty := 0 , 0 // 定义每循环一个圈的起始位置
365+ loop := min (rows, columns) / 2
366+ mid := min (rows, columns) / 2
367+ count := 0 // 用来给矩阵中每一个空格赋值
368+ offset := 1 // 每一圈循环,需要控制每一条边遍历的长度
369+ for loop > 0 {
370+ i , j := startx, starty
371+
372+ // 模拟填充上行从左到右(左闭右开)
373+ for ; j < starty + columns - offset; j++ {
374+ res[count] = matrix[startx][j]
375+ count++
376+ }
377+ // 模拟填充右列从上到下(左闭右开)
378+ for ; i < startx + rows - offset; i++ {
379+ res[count] = matrix[i][j]
380+ count++
381+ }
382+ // 模拟填充下行从右到左(左闭右开)
383+ for ; j > starty; j-- {
384+ res[count] = matrix[i][j]
385+ count++
386+ }
387+ // 模拟填充左列从下到上(左闭右开)
388+ for ; i > startx; i-- {
389+ res[count] = matrix[i][starty]
390+ count++
391+ }
392+
393+ // 第二圈开始的时候,起始位置要各自加1, 例如:第一圈起始位置是(0, 0),第二圈起始位置是(1, 1)
394+ startx++
395+ starty++
396+
397+ // offset 控制每一圈里每一条边遍历的长度
398+ offset += 2
399+ loop--
400+ }
401+
402+ // 如果min(rows, columns)为奇数的话,需要单独给矩阵最中间的位置赋值
403+ if min (rows, columns) % 2 == 1 {
404+ if rows > columns {
405+ for i := mid; i < mid + rows - columns + 1 ; i++ {
406+ res[count] = matrix[i][mid]
407+ count++
408+ }
409+ } else {
410+ for i := mid; i < mid + columns - rows + 1 ; i++ {
411+ res[count] = matrix[mid][i]
412+ count++
413+ }
414+ }
415+ }
416+ return res
417+ }
418+
419+ func min (x , y int ) int {
420+ if x < y {
421+ return x
422+ }
423+ return y
424+ }
425+ ```
426+
351427
352428<p align =" center " >
353429<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
0 commit comments