順時針打印矩陣
輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字。
示例 1:
輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]
示例 2:
輸入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
輸出:[1,2,3,4,8,12,11,10,9,5,6,7]
Go語言實現
package main
func printMatrix(matrix [][]int) []int {
result := []int{}
row := len(matrix)
if row == 0 {
return result
}
column := len(matrix[0])
if column == 0 {
return result
}
//定義下標變量
top := 0
bottom := row - 1
left := 0
right := column - 1
for left <= right && top <= bottom {
//從左往右,行數爲top,列數從left開始,+1直到right
for i := left; i <= right; i++ {
result = append(result, matrix[top][i])
}
//從上往下,行數從top+1開始,+1直到bottom,列數爲right
for i := top + 1; i <= bottom; i++ {
result = append(result, matrix[i][right])
}
//row不重複,從右往左,行數爲bottom,列數從right-1開始,-1直到left
if top != bottom {
for i := right - 1; i >= left; i-- {
result = append(result, matrix[bottom][i])
}
}
//column不重複,從下往上,行數從bottom-1開始,-1直到top-1,所以沒有等號
if left != right {
for i := bottom - 1; i > top; i-- {
result = append(result, matrix[i][left])
}
}
//一圈結束
left++
right--
top++
bottom--
}
return result
}
func main(){
a:=[][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
fmt.Println(printMatrix(a))
}