标签:++ code 完整 测试 square time amp tee tin
用GO实现二维数组的顺时针旋转,总体思想为,确定好正方形二维数组的边界,从边开始旋转,转完整个边界之后把二维数组向内缩小一个边界,找到边界,继续旋转(交换)....
例如:
{ 1, 2, 3, 4}
{ 5, 6, 7, 8}
{ 9,10,11,12}
{13,14,15,16}
旋转后:
{13, 9, 5, 1}
{14,10, 6, 2}
{15,11, 7, 3}
{16,12, 8, 4}
1 package algorithm 2 3 func rotateSquare(arr *[][]int) { 4 topLeftRow := 0 5 topLeftCol := 0 6 lowRightRow := len(*arr) - 1 7 lowRightCol := len((*arr)[0]) - 1 8 for ; topLeftRow <= lowRightRow && topLeftCol <= lowRightCol; { 9 rotateEdge(arr, topLeftRow, topLeftCol, lowRightRow, lowRightCol) 10 topLeftRow++ 11 topLeftCol++ 12 lowRightRow-- 13 lowRightCol-- 14 } 15 } 16 17 func rotateEdge(arr *[][]int, topLeftRow, topLeftCol, lowRightRow, lowRightCol int) { 18 times := lowRightCol - topLeftCol 19 for i := 0; i < times; i++ { 20 origin := (*arr)[topLeftRow][topLeftCol+i] 21 (*arr)[topLeftRow][topLeftCol+i] = (*arr)[lowRightRow-i][topLeftCol] 22 (*arr)[lowRightRow-i][topLeftCol] = (*arr)[lowRightRow][lowRightCol-i] 23 (*arr)[lowRightRow][lowRightCol-i] = (*arr)[topLeftRow+i][lowRightCol] 24 (*arr)[topLeftRow+i][lowRightCol] = origin 25 } 26 }
测试代码为
1 package algorithm 2 3 import ( 4 "testing" 5 "fmt" 6 ) 7 8 func Test_rotateSquare(t *testing.T) { 9 arr := [][]int{ 10 {1, 2, 3, 4}, 11 {5, 6, 7, 8}, 12 {9, 10, 11, 12}, 13 {13, 14, 15, 16}, 14 } 15 rotateSquare(&arr) 16 fmt.Println(arr) 17 }
标签:++ code 完整 测试 square time amp tee tin
原文地址:https://www.cnblogs.com/hsnblog/p/9452064.html