题目:
给定一个整形矩阵matrix,请按照转圈的方式打印它。
例如:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
打印结果为:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
要求:额外空间复杂度为O(1)
代码:
package main
import (
"fmt"
)
func calPrintNum(arr [][]int, tR, tC, dR, dC int) {
if dR <= 0 || dC <= 0 {
return
}
for j := tC; j < dC; j++ {
fmt.Printf("%d ", arr[tR][j])
}
for i := tR; i < dR; i++ {
fmt.Printf("%d ", arr[i][dC-1])
}
for j := dC; j > tC; j-- {
fmt.Printf("%d ", arr[dR-1][j])
}
for i := dR; i > tR; i-- {
fmt.Printf("%d ", arr[i][tC])
}
}
func getMin(a, b int) int {
if a < b {
return a
}
return b
}
func main() {
// matrix := [][]int {
// {1, 2, 3, 4, 5},
// {6, 7, 8, 9, 10},
// {11, 12, 13, 14, 15},
// {16, 17, 18, 19, 20},
// }
matrix := [][]int {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16},
}
dR := 3
dC := 3
tR := 0
tC := 0
calNum := getMin(dR, dC)
for i := 0; i < calNum; i++ {
calPrintNum(matrix, tR, tC, dR, dC)
tR++
tC++
dR--
dC--
}
}