之字形打印矩陣

例如:矩陣爲arr := [][]int {
{1,2,3,4,5,6,7},
{8,9,10,11,12,13,14},
{15,16,17,18,19,20,21},
}
打印順序爲:1,8,2,3,9,15,16,10,4,5,11,17,18,12,6,7,13,19,20,14,21

設計思想爲,將矩陣分爲:[1][2,8][3,9,15][4,10,16]....[21]這樣成一條斜線的一組一組的數據,分別打印組中數據,使用座標a表示這條斜線的上邊界的點,使用座標b表示這條斜線的下邊界的點,每打印一條斜線a點向右走,走到頭向下走,b點向下走,走到頭向右走,直到a點的行大於了b點的行,中止,整個矩陣打印完畢。

代碼:
 1 func printMatrix(arr [][]int) {  2     if arr == nil {  3         println("Matrix is empty")  4         return
 5  }  6     row := len(arr) - 1
 7     col := len(arr[0]) - 1
 8     a1, a2 := 0, 0
 9     b1, b2 := 0, 0
10     var aPrint bool
11     aPrint = true
12     for a1 <= b1 { 13  printLine(arr, a1, a2, b1, b2, aPrint) 14         if a2 < col { 15             a2++
16         } else { 17             a1++
18  } 19         if b1 < row { 20             b1++
21         } else { 22             b2++
23  } 24         aPrint = !aPrint 25  } 26 } 27 
28 func printLine(arr [][]int, a1, a2, b1, b2 int, aPrint bool) { 29     if aPrint { 30         for ; a1 <= b1; { 31  println(arr[a1][a2]) 32             a1++
33             a2--
34  } 35     } else { 36         for ; b2 <= a2; { 37  println(arr[b1][b2]) 38             b1--
39             b2++
40  } 41  } 42 }

測試代碼爲:測試

1 func Test_printMatrix(t *testing.T) { 2     arr := [][]int { 3         {1,2,3,4,5,6,7}, 4         {8,9,10,11,12,13,14}, 5         {15,16,17,18,19,20,21}, 6  } 7  printMatrix(arr) 8 }
相關文章
相關標籤/搜索