u
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
package top100liked
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
|
||||
|
||||
func spiralOrder(matrix [][]int) []int {
|
||||
rowLength := len(matrix)
|
||||
columeLength := len(matrix[0])
|
||||
// 0 表示从左到右,1 表示从上到下,2 表示从右往左,3 表示从下到上
|
||||
direction := 0
|
||||
count := 0
|
||||
path := make([][]int, len(matrix))
|
||||
for i := range path {
|
||||
path[i] = make([]int, len(matrix[0]))
|
||||
}
|
||||
|
||||
r, c := 0, 0
|
||||
result := []int{}
|
||||
for count < len(matrix)*len(matrix[0]) {
|
||||
switch direction {
|
||||
case 0:
|
||||
for ; c < columeLength; c++ {
|
||||
if path[r][c] == 1 {
|
||||
break
|
||||
}
|
||||
path[r][c] = 1
|
||||
result = append(result, matrix[r][c])
|
||||
count++
|
||||
}
|
||||
r++
|
||||
c--
|
||||
direction = 1
|
||||
case 1:
|
||||
for ; r < rowLength; r++ {
|
||||
if path[r][c] == 1 {
|
||||
break
|
||||
}
|
||||
path[r][c] = 1
|
||||
result = append(result, matrix[r][c])
|
||||
count++
|
||||
}
|
||||
c--
|
||||
r--
|
||||
direction = 2
|
||||
case 2:
|
||||
for ; c >= 0; c-- {
|
||||
if path[r][c] == 1 {
|
||||
break
|
||||
}
|
||||
path[r][c] = 1
|
||||
result = append(result, matrix[r][c])
|
||||
count++
|
||||
}
|
||||
r--
|
||||
c++
|
||||
direction = 3
|
||||
case 3:
|
||||
for ; r >= 0; r-- {
|
||||
if path[r][c] == 1 {
|
||||
break
|
||||
}
|
||||
path[r][c] = 1
|
||||
result = append(result, matrix[r][c])
|
||||
count++
|
||||
}
|
||||
c++
|
||||
r++
|
||||
direction = 0
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TestS19(t *testing.T) {
|
||||
var matrix [][]int
|
||||
matrix = [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
|
||||
fmt.Printf("%+v\n", spiralOrder(matrix))
|
||||
matrix = [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}
|
||||
fmt.Printf("%+v\n", spiralOrder(matrix))
|
||||
}
|
||||
Reference in New Issue
Block a user