之字形打印矩阵
例如:矩阵为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 }